@stacksjs/buddy 0.75.615 → 0.75.617
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{existsSync,readFileSync}from"node:fs";import{nextBuildNumber}from"@stacksjs/bumpx";const API="https://api.appstoreconnect.apple.com";export function appStoreConnectCredentials(env=process.env){const keyId=env.APP_STORE_CONNECT_KEY_ID?.trim();const issuerId=env.APP_STORE_CONNECT_ISSUER_ID?.trim();let privateKey=env.APP_STORE_CONNECT_PRIVATE_KEY?.trim();const keyPath=env.APP_STORE_CONNECT_PRIVATE_KEY_PATH?.trim();if(!privateKey&&keyPath&&existsSync(keyPath))privateKey=readFileSync(keyPath,"utf8").trim();if(!keyId||!issuerId||!privateKey)return null;return{keyId,issuerId,privateKey:privateKey.replace(/\\n/g,`
|
|
2
|
-
`)}}function base64url(bytes){const buffer=typeof bytes==="string"?Buffer.from(bytes):Buffer.from(bytes);return buffer.toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")}export async function appStoreConnectToken(credentials,now=Date.now()){const pem=credentials.privateKey.replace(/-----(BEGIN|END) PRIVATE KEY-----/g,"").replace(/\s+/g,"");const key=await crypto.subtle.importKey("pkcs8",Buffer.from(pem,"base64"),{name:"ECDSA",namedCurve:"P-256"},false,["sign"]);const iat=Math.floor(now/1000);const header=base64url(JSON.stringify({alg:"ES256",kid:credentials.keyId,typ:"JWT"}));const payload=base64url(JSON.stringify({iss:credentials.issuerId,iat,exp:iat+20*60,aud:"appstoreconnect-v1"}));const signature=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},key,Buffer.from(`${header}.${payload}`));return`${header}.${payload}.${base64url(new Uint8Array(signature))}`}export class AppStoreConnect{token;fetchImpl;tokenProvider;renewAt=Number.POSITIVE_INFINITY;renewing;constructor(token,fetchImpl=fetch){this.token=token;this.fetchImpl=fetchImpl}static async connect(credentials,fetchImpl){const{keyId,issuerId,privateKey}=credentials;const issue=async()=>{const now=Date.now();return{token:await appStoreConnectToken({keyId,issuerId,privateKey},now),renewAt:now+15*60000}};const issued=await issue();const api=new AppStoreConnect(issued.token,fetchImpl);api.tokenProvider=issue;api.renewAt=issued.renewAt;return api}async authorization(){if(this.tokenProvider&&Date.now()>=this.renewAt){if(!this.renewing){this.renewing=this.tokenProvider().then((issued)=>{this.token=issued.token;this.renewAt=issued.renewAt}).finally(()=>{this.renewing=undefined})}await this.renewing}return`Bearer ${this.token}`}async request(path,init={}){const response=await this.fetchImpl(`${API}${path}`,{...init,signal:init.signal??AbortSignal.timeout(30000),headers:{Authorization:await this.authorization(),"Content-Type":"application/json",...init.headers}});if(!response.ok){const body=await response.text().catch(()=>"");throw new Error(`App Store Connect ${init.method??"GET"} ${path} answered ${response.status}${body?`: ${body.slice(0,300)}`:""}`)}return response.status===204?null:await response.json()}async pages(path){const rows=[];const visited=new Set;while(path){if(visited.has(path))throw new Error("App Store Connect repeated a pagination link");visited.add(path);const page=await this.request(path);rows.push(...page?.data??[]);if(!page?.links?.next)break;const next=new URL(page.links.next,API);if(next.origin!==API||!next.pathname.startsWith("/v1/")||next.username||next.password)throw new Error("App Store Connect returned an unsafe pagination link");path=next.pathname+next.search}return rows}async internalTestFlightGroups(appId,names){if(!Array.isArray(names)||names.some((name)=>typeof name!=="string"||!name.trim()))throw new Error("ios.testFlightGroups must contain nonempty internal group names");if(!names.length)return[];const groups=(await this.pages(`/v1/apps/${encodeURIComponent(appId)}/betaGroups?limit=200&fields[betaGroups]=name,isInternalGroup`)).map((row)=>({id:String(row.id),name:String(row.attributes?.name??""),isInternalGroup:row.attributes?.isInternalGroup===true}));return[...new Set(names.map((name)=>name.trim()))].map((name)=>{const matching=groups.filter((group)=>group.name===name);if(matching.length!==1||!matching[0].isInternalGroup)throw new Error(`TestFlight group ${JSON.stringify(name)} must name one existing internal group for this app`);return matching[0]})}async assignBuildToInternalGroups(appId,build,names){if(build.processingState!=="VALID"||build.expired)throw new Error("Only a processed, unexpired build can be distributed to TestFlight");const groups=await this.internalTestFlightGroups(appId,names);if(!groups.length)return groups;const assigned=new Set((await this.buildTestFlightGroups(build.id)).map((group)=>group.id));for(const group of groups){if(assigned.has(group.id))continue;await this.request(`/v1/betaGroups/${encodeURIComponent(group.id)}/relationships/builds`,{method:"POST",body:JSON.stringify({data:[{type:"builds",id:build.id}]})})}return groups}async buildTestFlightGroups(buildId){return this.pages(`/v1/betaGroups?filter[builds]=${encodeURIComponent(buildId)}&limit=200&fields[betaGroups]=name,isInternalGroup`)}async testFlightStatus(buildId){const[detail,groups]=await Promise.all([this.request(`/v1/builds/${encodeURIComponent(buildId)}/buildBetaDetail`),this.buildTestFlightGroups(buildId)]);return{internalBuildState:String(detail?.data?.attributes?.internalBuildState??""),groupIds:groups.map((group)=>String(group.id))}}async deliverBuild(appId,version,number,options){const interval=options.intervalMs??30000;const keep=options.keepBuilds??1;if(!Number.isFinite(options.timeoutMs)||options.timeoutMs<0||!Number.isFinite(interval)||interval<=0||!Number.isSafeInteger(keep)||keep<0)throw new Error("TestFlight delivery needs a nonnegative wait/retention count and a positive polling interval");const now=options.now??Date.now;const sleep=options.sleep??((ms)=>new Promise((resolve)=>setTimeout(resolve,ms)));const start=now();const groups=await this.internalTestFlightGroups(appId,options.groups??[]);let appliedBuild;for(;;){const build=await this.build(appId,version,number);if(build?.expired||build&&["FAILED","INVALID"].includes(build.processingState))throw new Error(`TestFlight build ${number} is ${build.expired?"expired":build.processingState}`);if(build?.processingState==="VALID"){if(appliedBuild!==build.id){if(options.notes&&Object.keys(options.notes).length)await this.setWhatToTest(build.id,options.notes);await this.assignBuildToInternalGroups(appId,build,options.groups??[]);appliedBuild=build.id}const status=await this.testFlightStatus(build.id);if(status.internalBuildState==="IN_BETA_TESTING"&&groups.every((group)=>status.groupIds.includes(group.id))){if(options.timeoutMs>0&&now()-start>options.timeoutMs)return null;const older=(await this.builds(appId)).filter((candidate)=>candidate.number<number);for(const retiring of buildsToExpire(older,keep))await this.expire(retiring.id);return build}}const elapsed=now()-start;if(elapsed+interval>options.timeoutMs)return null;options.onWait?.(elapsed);await sleep(interval)}}async appId(bundleId){const body=await this.request(`/v1/apps?filter[bundleId]=${encodeURIComponent(bundleId)}&limit=1`);const id=body?.data?.[0]?.id;if(!id)throw new Error(`App Store Connect has no app with the bundle id ${bundleId}`);return id}async latestXcodeCloudRun(appId){const products=await this.request(`/v1/ciProducts?filter[app]=${appId}&limit=1`);const productId=products?.data?.[0]?.id;if(!productId)return null;const runs=await this.request(`/v1/ciProducts/${productId}/buildRuns?sort=-number&limit=1&fields[ciBuildRuns]=number`);const number=Number(runs?.data?.[0]?.attributes?.number);return Number.isSafeInteger(number)&&number>=0?number:null}async builds(appId){const rows=await this.pages(`/v1/builds?filter[app]=${encodeURIComponent(appId)}&sort=-uploadedDate&limit=200&fields[builds]=version,uploadedDate,processingState,expired`);return rows.map((build)=>({id:build.id,number:Number(build.attributes?.version),uploadedDate:String(build.attributes?.uploadedDate??""),processingState:String(build.attributes?.processingState??""),expired:Boolean(build.attributes?.expired)}))}async build(appId,version,number){const query=`filter[app]=${appId}&filter[version]=${encodeURIComponent(String(number))}&filter[preReleaseVersion.version]=${encodeURIComponent(version)}&limit=1&fields[builds]=version,uploadedDate,processingState,expired`;const build=(await this.request(`/v1/builds?${query}`))?.data?.[0];return build?{id:build.id,number:Number(build.attributes?.version),uploadedDate:String(build.attributes?.uploadedDate??""),processingState:String(build.attributes?.processingState??""),expired:Boolean(build.attributes?.expired)}:null}async setWhatToTest(buildId,notes){const existing=await this.request(`/v1/builds/${buildId}/betaBuildLocalizations?limit=50&fields[betaBuildLocalizations]=locale,whatsNew`);const byLocale=new Map((existing?.data??[]).map((row)=>[String(row.attributes?.locale),String(row.id)]));for(const[locale,whatsNew]of Object.entries(notes)){const id=byLocale.get(locale);if(id){await this.request(`/v1/betaBuildLocalizations/${id}`,{method:"PATCH",body:JSON.stringify({data:{type:"betaBuildLocalizations",id,attributes:{whatsNew}}})})}else{await this.request("/v1/betaBuildLocalizations",{method:"POST",body:JSON.stringify({data:{type:"betaBuildLocalizations",attributes:{locale,whatsNew},relationships:{build:{data:{type:"builds",id:buildId}}}}})})}}}async expire(buildId){await this.request(`/v1/builds/${buildId}`,{method:"PATCH",body:JSON.stringify({data:{type:"builds",id:buildId,attributes:{expired:true}}})})}}export function buildsToExpire(builds,keep=1){const live=builds.filter((build)=>!build.expired&&build.processingState==="VALID").sort((a,b)=>b.number-a.number);return live.slice(Math.max(0,keep))}export function tagForXcodeCloudRun(version,latestRun){return`v${version}-build.${nextBuildNumber(latestRun)}`}export async function waitForBuild(api,appId,version,number,options){const sleep=options.sleep??((ms)=>new Promise((resolve)=>setTimeout(resolve,ms)));const now=options.now??Date.now;const interval=options.intervalMs??30000;const start=now();for(;;){const build=await api.build(appId,version,number);if(build)return build;const elapsed=now()-start;if(elapsed+interval>options.timeoutMs)return null;options.onWait?.(elapsed);await sleep(interval)}}
|
|
2
|
+
`)}}function base64url(bytes){const buffer=typeof bytes==="string"?Buffer.from(bytes):Buffer.from(bytes);return buffer.toString("base64").replace(/=+$/,"").replace(/\+/g,"-").replace(/\//g,"_")}export async function appStoreConnectToken(credentials,now=Date.now()){const pem=credentials.privateKey.replace(/-----(BEGIN|END) PRIVATE KEY-----/g,"").replace(/\s+/g,"");const key=await crypto.subtle.importKey("pkcs8",Buffer.from(pem,"base64"),{name:"ECDSA",namedCurve:"P-256"},false,["sign"]);const iat=Math.floor(now/1000);const header=base64url(JSON.stringify({alg:"ES256",kid:credentials.keyId,typ:"JWT"}));const payload=base64url(JSON.stringify({iss:credentials.issuerId,iat,exp:iat+20*60,aud:"appstoreconnect-v1"}));const signature=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},key,Buffer.from(`${header}.${payload}`));return`${header}.${payload}.${base64url(new Uint8Array(signature))}`}export class AppStoreConnect{token;fetchImpl;tokenProvider;renewAt=Number.POSITIVE_INFINITY;renewing;constructor(token,fetchImpl=fetch){this.token=token;this.fetchImpl=fetchImpl}static async connect(credentials,fetchImpl){const{keyId,issuerId,privateKey}=credentials;const issue=async()=>{const now=Date.now();return{token:await appStoreConnectToken({keyId,issuerId,privateKey},now),renewAt:now+15*60000}};const issued=await issue();const api=new AppStoreConnect(issued.token,fetchImpl);api.tokenProvider=issue;api.renewAt=issued.renewAt;return api}async authorization(){if(this.tokenProvider&&Date.now()>=this.renewAt){if(!this.renewing){this.renewing=this.tokenProvider().then((issued)=>{this.token=issued.token;this.renewAt=issued.renewAt}).finally(()=>{this.renewing=undefined})}await this.renewing}return`Bearer ${this.token}`}async request(path,init={}){const response=await this.fetchImpl(`${API}${path}`,{...init,signal:init.signal??AbortSignal.timeout(30000),headers:{Authorization:await this.authorization(),"Content-Type":"application/json",...init.headers}});if(!response.ok){const body=await response.text().catch(()=>"");throw new Error(`App Store Connect ${init.method??"GET"} ${path} answered ${response.status}${body?`: ${body.slice(0,300)}`:""}`)}return response.status===204?null:await response.json()}async pages(path){const rows=[];const visited=new Set;while(path){if(visited.has(path))throw new Error("App Store Connect repeated a pagination link");visited.add(path);const page=await this.request(path);rows.push(...page?.data??[]);if(!page?.links?.next)break;const next=new URL(page.links.next,API);if(next.origin!==API||!next.pathname.startsWith("/v1/")||next.username||next.password)throw new Error("App Store Connect returned an unsafe pagination link");path=next.pathname+next.search}return rows}async internalTestFlightGroups(appId,names){if(!Array.isArray(names)||names.some((name)=>typeof name!=="string"||!name.trim()))throw new Error("ios.testFlightGroups must contain nonempty internal group names");if(!names.length)return[];const groups=(await this.pages(`/v1/apps/${encodeURIComponent(appId)}/betaGroups?limit=200&fields[betaGroups]=name,isInternalGroup,hasAccessToAllBuilds`)).map((row)=>({id:String(row.id),name:String(row.attributes?.name??""),isInternalGroup:row.attributes?.isInternalGroup===true,hasAccessToAllBuilds:row.attributes?.hasAccessToAllBuilds===true}));return[...new Set(names.map((name)=>name.trim()))].map((name)=>{const matching=groups.filter((group)=>group.name===name);if(matching.length!==1||!matching[0].isInternalGroup)throw new Error(`TestFlight group ${JSON.stringify(name)} must name one existing internal group for this app`);return matching[0]})}async assignBuildToInternalGroups(appId,build,names){if(build.processingState!=="VALID"||build.expired)throw new Error("Only a processed, unexpired build can be distributed to TestFlight");const groups=await this.internalTestFlightGroups(appId,names);if(!groups.length)return groups;const assigned=new Set((await this.buildTestFlightGroups(build.id)).map((group)=>group.id));for(const group of groups){if(assigned.has(group.id)||group.hasAccessToAllBuilds)continue;await this.request(`/v1/betaGroups/${encodeURIComponent(group.id)}/relationships/builds`,{method:"POST",body:JSON.stringify({data:[{type:"builds",id:build.id}]})})}return groups}async buildTestFlightGroups(buildId){return this.pages(`/v1/betaGroups?filter[builds]=${encodeURIComponent(buildId)}&limit=200&fields[betaGroups]=name,isInternalGroup`)}async testFlightStatus(buildId){const[detail,groups]=await Promise.all([this.request(`/v1/builds/${encodeURIComponent(buildId)}/buildBetaDetail`),this.buildTestFlightGroups(buildId)]);return{internalBuildState:String(detail?.data?.attributes?.internalBuildState??""),groupIds:groups.map((group)=>String(group.id))}}async deliverBuild(appId,version,number,options){const interval=options.intervalMs??30000;const keep=options.keepBuilds??1;if(!Number.isFinite(options.timeoutMs)||options.timeoutMs<0||!Number.isFinite(interval)||interval<=0||!Number.isSafeInteger(keep)||keep<0)throw new Error("TestFlight delivery needs a nonnegative wait/retention count and a positive polling interval");const now=options.now??Date.now;const sleep=options.sleep??((ms)=>new Promise((resolve)=>setTimeout(resolve,ms)));const start=now();const groups=await this.internalTestFlightGroups(appId,options.groups??[]);let appliedBuild;for(;;){const build=await this.build(appId,version,number);if(build?.expired||build&&["FAILED","INVALID"].includes(build.processingState))throw new Error(`TestFlight build ${number} is ${build.expired?"expired":build.processingState}`);if(build?.processingState==="VALID"){if(appliedBuild!==build.id){if(options.notes&&Object.keys(options.notes).length)await this.setWhatToTest(build.id,options.notes);await this.assignBuildToInternalGroups(appId,build,options.groups??[]);appliedBuild=build.id}const status=await this.testFlightStatus(build.id);if(status.internalBuildState==="IN_BETA_TESTING"&&groups.every((group)=>status.groupIds.includes(group.id))){if(options.timeoutMs>0&&now()-start>options.timeoutMs)return null;const older=(await this.builds(appId)).filter((candidate)=>candidate.number<number);for(const retiring of buildsToExpire(older,keep))await this.expire(retiring.id);return build}}const elapsed=now()-start;if(elapsed+interval>options.timeoutMs)return null;options.onWait?.(elapsed);await sleep(interval)}}async appId(bundleId){const body=await this.request(`/v1/apps?filter[bundleId]=${encodeURIComponent(bundleId)}&limit=1`);const id=body?.data?.[0]?.id;if(!id)throw new Error(`App Store Connect has no app with the bundle id ${bundleId}`);return id}async latestXcodeCloudRun(appId){const products=await this.request(`/v1/ciProducts?filter[app]=${appId}&limit=1`);const productId=products?.data?.[0]?.id;if(!productId)return null;const runs=await this.request(`/v1/ciProducts/${productId}/buildRuns?sort=-number&limit=1&fields[ciBuildRuns]=number`);const number=Number(runs?.data?.[0]?.attributes?.number);return Number.isSafeInteger(number)&&number>=0?number:null}async builds(appId){const rows=await this.pages(`/v1/builds?filter[app]=${encodeURIComponent(appId)}&sort=-uploadedDate&limit=200&fields[builds]=version,uploadedDate,processingState,expired`);return rows.map((build)=>({id:build.id,number:Number(build.attributes?.version),uploadedDate:String(build.attributes?.uploadedDate??""),processingState:String(build.attributes?.processingState??""),expired:Boolean(build.attributes?.expired)}))}async build(appId,version,number){const query=`filter[app]=${appId}&filter[version]=${encodeURIComponent(String(number))}&filter[preReleaseVersion.version]=${encodeURIComponent(version)}&limit=1&fields[builds]=version,uploadedDate,processingState,expired`;const build=(await this.request(`/v1/builds?${query}`))?.data?.[0];return build?{id:build.id,number:Number(build.attributes?.version),uploadedDate:String(build.attributes?.uploadedDate??""),processingState:String(build.attributes?.processingState??""),expired:Boolean(build.attributes?.expired)}:null}async setWhatToTest(buildId,notes){const existing=await this.request(`/v1/builds/${buildId}/betaBuildLocalizations?limit=50&fields[betaBuildLocalizations]=locale,whatsNew`);const byLocale=new Map((existing?.data??[]).map((row)=>[String(row.attributes?.locale),String(row.id)]));for(const[locale,whatsNew]of Object.entries(notes)){const id=byLocale.get(locale);if(id){await this.request(`/v1/betaBuildLocalizations/${id}`,{method:"PATCH",body:JSON.stringify({data:{type:"betaBuildLocalizations",id,attributes:{whatsNew}}})})}else{await this.request("/v1/betaBuildLocalizations",{method:"POST",body:JSON.stringify({data:{type:"betaBuildLocalizations",attributes:{locale,whatsNew},relationships:{build:{data:{type:"builds",id:buildId}}}}})})}}}async expire(buildId){await this.request(`/v1/builds/${buildId}`,{method:"PATCH",body:JSON.stringify({data:{type:"builds",id:buildId,attributes:{expired:true}}})})}}export function buildsToExpire(builds,keep=1){const live=builds.filter((build)=>!build.expired&&build.processingState==="VALID").sort((a,b)=>b.number-a.number);return live.slice(Math.max(0,keep))}export function tagForXcodeCloudRun(version,latestRun){return`v${version}-build.${nextBuildNumber(latestRun)}`}export async function waitForBuild(api,appId,version,number,options){const sleep=options.sleep??((ms)=>new Promise((resolve)=>setTimeout(resolve,ms)));const now=options.now??Date.now;const interval=options.intervalMs??30000;const start=now();for(;;){const build=await api.build(appId,version,number);if(build)return build;const elapsed=now()-start;if(elapsed+interval>options.timeoutMs)return null;options.onWait?.(elapsed);await sleep(interval)}}
|
|
@@ -544,6 +544,15 @@ export declare function reportRecoveryReconcile(logger: Pick<typeof log, 'info'
|
|
|
544
544
|
* Everywhere else the log says where the encrypted copy was written.
|
|
545
545
|
*/
|
|
546
546
|
export declare function reportMailboxCredentials(logger: Pick<typeof log, 'info' | 'warn'>, created: Array<Pick<ResolvedMailbox, 'address' | 'localPart' | 'password' | 'generated'>>, options: { interactive: boolean, persisted: boolean }): void;
|
|
547
|
+
/**
|
|
548
|
+
* The account a sending service relays through: its own sender, when
|
|
549
|
+
* `email.server.relay` is on and that sender is one of its declared mailboxes.
|
|
550
|
+
*
|
|
551
|
+
* Only a declared mailbox, on the app's own domain, in a shape that is
|
|
552
|
+
* plainly an address: the name goes into the mail server's configuration,
|
|
553
|
+
* where it decides who may carry other domains' mail.
|
|
554
|
+
*/
|
|
555
|
+
export declare function relayAccountFromConfig(cfg: any, domain: string | undefined, declared: Iterable<string>): { account?: string, problem?: string };
|
|
547
556
|
/**
|
|
548
557
|
* Give each mailbox that asked for a generated password one, and save it,
|
|
549
558
|
* before the app's environment ships.
|
package/dist/commands/deploy.js
CHANGED
|
@@ -47,15 +47,16 @@ rm -f /etc/systemd/system/mail-health.service /etc/systemd/system/mail-health.ti
|
|
|
47
47
|
rm -f /usr/local/sbin/mail-health-check /etc/systemd/system/mail.service.d/reliability.conf
|
|
48
48
|
rmdir /etc/systemd/system/mail.service.d 2>/dev/null || true
|
|
49
49
|
systemctl daemon-reload
|
|
50
|
-
systemctl reset-failed`;try{execFileSync("ssh",[...sshArgs,"bash","-s"],{input:script,encoding:"utf8",stdio:["pipe","pipe","pipe"]});logger.success("Mail: removed the detached health timer from the application box")}catch(err){logger.warn(`Mail: could not remove the detached health timer: ${getErrorMessage(err)}`)}}export function resolveHetznerApiToken(tsCloudConfig){return tsCloudConfig?.hetzner?.apiToken||process.env.HCLOUD_TOKEN||process.env.HETZNER_API_TOKEN}export function assertAttachResidency(policy,box){assertComputeResidency(policy,box)}export function describeAttachLookupFailure(owner,environment,failure){if(failure?.kind==="no-token"){return`Attach target '${owner}': no Hetzner API token to look it up with, so no lookup was attempted. Set HCLOUD_TOKEN (or HETZNER_API_TOKEN, or hetzner.apiToken in config/cloud.ts).`}if(failure?.kind==="request-failed"){const where=failure.status>0?`returned HTTP ${failure.status}`:"could not be reached";return`Attach target '${owner}': the Hetzner API ${where}, so whether the box exists is unknown.`+(failure.detail?` ${failure.detail}`:"")+(failure.status===401||failure.status===403?" That is an auth failure, not a missing server: check the token is valid for this Hetzner project.":"")}return`Attach target '${owner}' has no reachable box for '${environment}'. Nothing matched ts-cloud/project=${owner},ts-cloud/environment=${environment},ts-cloud/role=app, and no server is named '${owner}-${environment}-app'. Is it provisioned (by its owner)?`}export async function resolveAttachTargetBox(owner,environment,tsCloudConfig){const token=resolveHetznerApiToken(tsCloudConfig);if(!token)return{box:null,failure:{kind:"no-token"}};const pick=(servers)=>servers.find((s)=>s?.status!=="off"&&s?.public_net?.ipv4?.ip)||servers[0];let requestFailure;const req=async(qs)=>{try{const res=await fetch(`https://api.hetzner.cloud/v1/servers?${qs}`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.text().catch(()=>"");requestFailure??={kind:"request-failed",status:res.status,detail:pollFailureDetail(body)};return[]}return(await res.json()).servers||[]}catch(err){requestFailure??={kind:"request-failed",status:0,detail:pollFailureDetail(getErrorMessage(err))};return[]}};const byLabel=await req(`label_selector=${encodeURIComponent(`ts-cloud/project=${owner},ts-cloud/environment=${environment},ts-cloud/role=app`)}`);const chosen=pick(byLabel)||pick(await req(`name=${encodeURIComponent(`${owner}-${environment}-app`)}`));if(!chosen)return{box:null,failure:requestFailure??{kind:"no-match"}};const{normalizePublicIpv6}=await import("@stacksjs/ts-cloud");if(typeof normalizePublicIpv6!=="function")log.warn("DNS: @stacksjs/ts-cloud does not export normalizePublicIpv6 - AAAA records will be skipped. Upgrade ts-cloud.");const reportedIpv6=chosen.public_net?.ipv6?.ip;return{box:{serverId:chosen.id,country:chosen.location?.country||chosen.datacenter?.location?.country,location:chosen.location?.name||chosen.datacenter?.location?.name,serverName:chosen.name,publicIp:chosen.public_net?.ipv4?.ip,publicIpv6:typeof normalizePublicIpv6==="function"?normalizePublicIpv6(reportedIpv6):undefined}}}export function canRevealSecrets(env=process.env,stdout=process.stdout){if(env.CI||env.CONTINUOUS_INTEGRATION||env.GITHUB_ACTIONS||env.BUILD_NUMBER||env.RUN_ID)return false;return Boolean(stdout.isTTY)}export function reportRecoveryReconcile(logger,out,declared){const pick=(key)=>[...out.matchAll(new RegExp(`^${key}:([^\\n]+)`,"gm"))].flatMap((m)=>m[1]?[m[1].trim()]:[]);const set=pick("RECOVERY_SET");const same=pick("RECOVERY_SAME");const kept=pick("RECOVERY_KEPT");const nobox=pick("RECOVERY_NOBOX");const old=pick("RECOVERY_OLDSERVER");const failed=pick("RECOVERY_FAIL");if(set.length)logger.success(`Mail: set the recovery address of ${set.join(", ")}`);if(kept.length)logger.info(`Mail: kept the recovery address the owner chose in webmail for ${kept.join(", ")} (recoveryPolicy: 'managed' overrides it)`);if(nobox.length)logger.warn(`Mail: no recovery address set for ${nobox.join(", ")}: the mailbox does not exist on the mail server yet`);if(old.length)logger.warn(`Mail: the mail server is too old for recovery addresses, so none was set for ${old.join(", ")}. Upgrade it (mail upgrade) and deploy again.`);if(failed.length)logger.warn(`Mail: the mail server refused the recovery address of ${failed.join(", ")}`);const seen=new Set([...set,...same,...kept,...nobox,...old,...failed]);const missing=declared.map((r)=>r.address).filter((address)=>!seen.has(address));if(missing.length)logger.warn(`Mail: the recovery address of ${missing.join(", ")} was not reconciled`)}function mailboxPasswordKey(box){return`MAIL_PASSWORD_${box.localPart.replace(/[^A-Z0-9]/g,"_")}`}export function reportMailboxCredentials(logger,created,options){const declared=created.filter((box)=>!box.generated);if(declared.length)logger.info(`Mail: created ${declared.length} mailbox(es) with their declared password (config/email.ts or MAIL_PASSWORD_<LOCALPART>): ${declared.map((box)=>box.address).join(", ")}`);const generated=created.filter((box)=>box.generated);if(!generated.length)return;if(options.interactive){logger.info(options.persisted?`Mail: created ${generated.length} mailbox(es) with generated passwords, saved encrypted to .env.production and shown once here:`:`Mail: created ${generated.length} mailbox(es) with generated passwords that were NOT saved - store them now, they are shown once:`);for(const box of generated)logger.info(` ${box.address} ${box.password}`);return}if(!options.persisted){logger.warn(`Mail: ${generated.length} mailbox(es) have generated passwords that were neither saved nor shown: ${generated.map((box)=>box.address).join(", ")}. Set ${generated.map(mailboxPasswordKey).join(", ")} and deploy again.`);return}logger.info(`Mail: created ${generated.length} mailbox(es) with generated passwords, saved encrypted to .env.production (not printed: this is not an interactive terminal):`);for(const box of generated)logger.info(` ${box.address} -> buddy env:get ${mailboxPasswordKey(box)} --file .env.production`)}export async function ensureMailboxPasswords(logger,file=".env.production",options={}){if(!(options.hasConfig??hasExplicitEmailConfig()))return[];const cfg=options.config??emailConfig??{};if(cfg.server?.enabled===false)return[];const domain=cfg.domain||(typeof cfg.from?.address==="string"&&cfg.from.address.includes("@")?cfg.from.address.split("@")[1]:undefined);if(!domain)return[];const generated=resolveMailboxesWithSkipped(cfg.mailboxes,domain,cfg.server?.generatePasswords===true).boxes.filter((box)=>box.generated);if(generated.length===0)return[];const save=options.save??(async(key,value,target)=>{const{setEnv}=await import("@stacksjs/env");return setEnv(key,value,{file:target})});const written=[];for(const box of generated){const key=mailboxPasswordKey(box);try{await save(key,box.password,file);process.env[key]=box.password;written.push(key)}catch(err){logger.warn(`Mail: could not save a generated password for ${box.address} to ${file} before the release: ${getErrorMessage(err)}`)}}if(written.length>0)logger.info(`Mail: generated ${written.length} mailbox password(s) and saved them encrypted to ${file}, so this release carries them: ${written.join(", ")}`);return written}export async function provisionMailTenant(ip,logger){if(!hasExplicitEmailConfig())return null;const cfg=emailConfig||{};if(cfg.server?.enabled===false)return null;const domain=cfg.domain||(typeof cfg.from?.address==="string"&&cfg.from.address.includes("@")?cfg.from.address.split("@")[1]:undefined);const declaredForwards=cfg.forwards&&typeof cfg.forwards==="object"?cfg.forwards:{};const forwards={...declaredForwards};const declaredBoxes=new Set(domain?resolveMailboxes(cfg.mailboxes,domain).map((b)=>b.address):[]);for(const[key,targets]of Object.entries(declaredForwards)){const at=key.indexOf("@");if(at===-1||declaredBoxes.has(key))continue;const localPart=key.slice(0,at);if(key.slice(at+1)!==domain||forwards[localPart])continue;forwards[localPart]=targets}const hasForwards=Object.keys(forwards).length>0;const generatePasswords=cfg.server?.generatePasswords===true;const resolved=domain?resolveMailboxesWithSkipped(cfg.mailboxes,domain,generatePasswords):{boxes:[],skipped:[]};let boxes=resolved.boxes;const interactive=canRevealSecrets();const generated=boxes.filter((box)=>box.generated);let persisted=true;if(generated.length>0){try{const{setEnv}=await import("@stacksjs/env");for(const box of generated){await setEnv(mailboxPasswordKey(box),box.password,{file:".env.production"})}logger.success(`Mail: generated and saved ${generated.length} mailbox password(s) to .env.production (encrypted)`)}catch(err){persisted=false;if(interactive){logger.warn(`Mail: could not save the generated password(s) to .env.production - they are printed below and will otherwise be regenerated next deploy: ${getErrorMessage(err)}`)}else{const unsaved=new Set(generated.map((box)=>box.address));boxes=boxes.filter((box)=>!unsaved.has(box.address));logger.warn(`Mail: could not save the generated password(s) to .env.production, and this is not an interactive terminal, so ${[...unsaved].join(", ")} were not created: ${getErrorMessage(err)}`)}}}if(resolved.skipped.length>0){logger.warn(`Mail: ${resolved.skipped.length} declared mailbox(es) were not created because no password was supplied: ${resolved.skipped.join(", ")}`);logger.info(`Set MAIL_PASSWORD_<LOCALPART> in the target environment (e.g. ${resolved.skipped[0]?.split("@")[0]?.toUpperCase().replace(/[^A-Z0-9]/g,"_")}) and run this again.`)}const declaredRecoveries=domain?resolveMailboxRecoveries(cfg.mailboxes,domain):{recoveries:[],invalid:[]};if(declaredRecoveries.invalid.length>0)logger.warn(`Mail: ignored the recovery address of ${declaredRecoveries.invalid.join(", ")} in config/email.ts: it must be a valid address outside the mailbox itself`);if(!domain&&!hasForwards)return null;const{execFileSync}=await import("node:child_process");const sshArgs=sshCliArgs(hetznerTarget(ip),{connectTimeoutSec:20});const forwardsB64=hasForwards?Buffer.from(JSON.stringify(forwards)).toString("base64"):"";const readme="Auto-forwarding rules, re-read on every message (edits take effect immediately, no restart). KEY = the delivered mailbox: the FULL address for per-domain isolated mailboxes (e.g. no-reply@app.com), or a bare local-part for legacy role mailboxes. VALUE = list of destination addresses; targets on a local domain are written straight to that mailbox Maildir, external targets are relayed. Managed by buddy deploy from config/email.ts (merge-based - hand edits to other keys are preserved).";const readmeB64=Buffer.from(readme).toString("base64");const boxesB64=boxes.length?Buffer.from(`${boxes.map((b)=>`${b.address} ${b.password} ${b.passwordPolicy}`).join(`
|
|
50
|
+
systemctl reset-failed`;try{execFileSync("ssh",[...sshArgs,"bash","-s"],{input:script,encoding:"utf8",stdio:["pipe","pipe","pipe"]});logger.success("Mail: removed the detached health timer from the application box")}catch(err){logger.warn(`Mail: could not remove the detached health timer: ${getErrorMessage(err)}`)}}export function resolveHetznerApiToken(tsCloudConfig){return tsCloudConfig?.hetzner?.apiToken||process.env.HCLOUD_TOKEN||process.env.HETZNER_API_TOKEN}export function assertAttachResidency(policy,box){assertComputeResidency(policy,box)}export function describeAttachLookupFailure(owner,environment,failure){if(failure?.kind==="no-token"){return`Attach target '${owner}': no Hetzner API token to look it up with, so no lookup was attempted. Set HCLOUD_TOKEN (or HETZNER_API_TOKEN, or hetzner.apiToken in config/cloud.ts).`}if(failure?.kind==="request-failed"){const where=failure.status>0?`returned HTTP ${failure.status}`:"could not be reached";return`Attach target '${owner}': the Hetzner API ${where}, so whether the box exists is unknown.`+(failure.detail?` ${failure.detail}`:"")+(failure.status===401||failure.status===403?" That is an auth failure, not a missing server: check the token is valid for this Hetzner project.":"")}return`Attach target '${owner}' has no reachable box for '${environment}'. Nothing matched ts-cloud/project=${owner},ts-cloud/environment=${environment},ts-cloud/role=app, and no server is named '${owner}-${environment}-app'. Is it provisioned (by its owner)?`}export async function resolveAttachTargetBox(owner,environment,tsCloudConfig){const token=resolveHetznerApiToken(tsCloudConfig);if(!token)return{box:null,failure:{kind:"no-token"}};const pick=(servers)=>servers.find((s)=>s?.status!=="off"&&s?.public_net?.ipv4?.ip)||servers[0];let requestFailure;const req=async(qs)=>{try{const res=await fetch(`https://api.hetzner.cloud/v1/servers?${qs}`,{headers:{Authorization:`Bearer ${token}`}});if(!res.ok){const body=await res.text().catch(()=>"");requestFailure??={kind:"request-failed",status:res.status,detail:pollFailureDetail(body)};return[]}return(await res.json()).servers||[]}catch(err){requestFailure??={kind:"request-failed",status:0,detail:pollFailureDetail(getErrorMessage(err))};return[]}};const byLabel=await req(`label_selector=${encodeURIComponent(`ts-cloud/project=${owner},ts-cloud/environment=${environment},ts-cloud/role=app`)}`);const chosen=pick(byLabel)||pick(await req(`name=${encodeURIComponent(`${owner}-${environment}-app`)}`));if(!chosen)return{box:null,failure:requestFailure??{kind:"no-match"}};const{normalizePublicIpv6}=await import("@stacksjs/ts-cloud");if(typeof normalizePublicIpv6!=="function")log.warn("DNS: @stacksjs/ts-cloud does not export normalizePublicIpv6 - AAAA records will be skipped. Upgrade ts-cloud.");const reportedIpv6=chosen.public_net?.ipv6?.ip;return{box:{serverId:chosen.id,country:chosen.location?.country||chosen.datacenter?.location?.country,location:chosen.location?.name||chosen.datacenter?.location?.name,serverName:chosen.name,publicIp:chosen.public_net?.ipv4?.ip,publicIpv6:typeof normalizePublicIpv6==="function"?normalizePublicIpv6(reportedIpv6):undefined}}}export function canRevealSecrets(env=process.env,stdout=process.stdout){if(env.CI||env.CONTINUOUS_INTEGRATION||env.GITHUB_ACTIONS||env.BUILD_NUMBER||env.RUN_ID)return false;return Boolean(stdout.isTTY)}export function reportRecoveryReconcile(logger,out,declared){const pick=(key)=>[...out.matchAll(new RegExp(`^${key}:([^\\n]+)`,"gm"))].flatMap((m)=>m[1]?[m[1].trim()]:[]);const set=pick("RECOVERY_SET");const same=pick("RECOVERY_SAME");const kept=pick("RECOVERY_KEPT");const nobox=pick("RECOVERY_NOBOX");const old=pick("RECOVERY_OLDSERVER");const failed=pick("RECOVERY_FAIL");if(set.length)logger.success(`Mail: set the recovery address of ${set.join(", ")}`);if(kept.length)logger.info(`Mail: kept the recovery address the owner chose in webmail for ${kept.join(", ")} (recoveryPolicy: 'managed' overrides it)`);if(nobox.length)logger.warn(`Mail: no recovery address set for ${nobox.join(", ")}: the mailbox does not exist on the mail server yet`);if(old.length)logger.warn(`Mail: the mail server is too old for recovery addresses, so none was set for ${old.join(", ")}. Upgrade it (mail upgrade) and deploy again.`);if(failed.length)logger.warn(`Mail: the mail server refused the recovery address of ${failed.join(", ")}`);const seen=new Set([...set,...same,...kept,...nobox,...old,...failed]);const missing=declared.map((r)=>r.address).filter((address)=>!seen.has(address));if(missing.length)logger.warn(`Mail: the recovery address of ${missing.join(", ")} was not reconciled`)}function mailboxPasswordKey(box){return`MAIL_PASSWORD_${box.localPart.replace(/[^A-Z0-9]/g,"_")}`}export function reportMailboxCredentials(logger,created,options){const declared=created.filter((box)=>!box.generated);if(declared.length)logger.info(`Mail: created ${declared.length} mailbox(es) with their declared password (config/email.ts or MAIL_PASSWORD_<LOCALPART>): ${declared.map((box)=>box.address).join(", ")}`);const generated=created.filter((box)=>box.generated);if(!generated.length)return;if(options.interactive){logger.info(options.persisted?`Mail: created ${generated.length} mailbox(es) with generated passwords, saved encrypted to .env.production and shown once here:`:`Mail: created ${generated.length} mailbox(es) with generated passwords that were NOT saved - store them now, they are shown once:`);for(const box of generated)logger.info(` ${box.address} ${box.password}`);return}if(!options.persisted){logger.warn(`Mail: ${generated.length} mailbox(es) have generated passwords that were neither saved nor shown: ${generated.map((box)=>box.address).join(", ")}. Set ${generated.map(mailboxPasswordKey).join(", ")} and deploy again.`);return}logger.info(`Mail: created ${generated.length} mailbox(es) with generated passwords, saved encrypted to .env.production (not printed: this is not an interactive terminal):`);for(const box of generated)logger.info(` ${box.address} -> buddy env:get ${mailboxPasswordKey(box)} --file .env.production`)}export function relayAccountFromConfig(cfg,domain,declared){const asked=cfg?.server?.relay;if(asked!==true&&!(typeof asked==="string"&&asked.trim()))return{};const named=typeof asked==="string"?asked.trim().toLowerCase():"";const address=named?named.includes("@")?named:`${named}@${(domain||"").toLowerCase()}`:typeof cfg.from?.address==="string"?cfg.from.address.trim().toLowerCase():"";if(!domain||!/^[a-z0-9][a-z0-9._+-]*@[a-z0-9][a-z0-9.-]*\.[a-z]{2,}$/.test(address)||!address.endsWith(`@${domain.toLowerCase()}`))return{problem:`email.server.relay is on, but its sender (${address||"unset"}) is not an address on ${domain||"the mail domain"}`};const boxes=new Set([...declared].map((box)=>box.toLowerCase()));if(!boxes.has(address))return{problem:`email.server.relay is on, but ${address} is not one of the declared mailboxes, so it cannot sign in to relay`};return{account:address}}export async function ensureMailboxPasswords(logger,file=".env.production",options={}){if(!(options.hasConfig??hasExplicitEmailConfig()))return[];const cfg=options.config??emailConfig??{};if(cfg.server?.enabled===false)return[];const domain=cfg.domain||(typeof cfg.from?.address==="string"&&cfg.from.address.includes("@")?cfg.from.address.split("@")[1]:undefined);if(!domain)return[];const generated=resolveMailboxesWithSkipped(cfg.mailboxes,domain,cfg.server?.generatePasswords===true).boxes.filter((box)=>box.generated);if(generated.length===0)return[];const save=options.save??(async(key,value,target)=>{const{setEnv}=await import("@stacksjs/env");return setEnv(key,value,{file:target})});const written=[];for(const box of generated){const key=mailboxPasswordKey(box);try{await save(key,box.password,file);process.env[key]=box.password;written.push(key)}catch(err){logger.warn(`Mail: could not save a generated password for ${box.address} to ${file} before the release: ${getErrorMessage(err)}`)}}if(written.length>0)logger.info(`Mail: generated ${written.length} mailbox password(s) and saved them encrypted to ${file}, so this release carries them: ${written.join(", ")}`);return written}export async function provisionMailTenant(ip,logger){if(!hasExplicitEmailConfig())return null;const cfg=emailConfig||{};if(cfg.server?.enabled===false)return null;const domain=cfg.domain||(typeof cfg.from?.address==="string"&&cfg.from.address.includes("@")?cfg.from.address.split("@")[1]:undefined);const declaredForwards=cfg.forwards&&typeof cfg.forwards==="object"?cfg.forwards:{};const forwards={...declaredForwards};const declaredBoxes=new Set(domain?resolveMailboxes(cfg.mailboxes,domain).map((b)=>b.address):[]);for(const[key,targets]of Object.entries(declaredForwards)){const at=key.indexOf("@");if(at===-1||declaredBoxes.has(key))continue;const localPart=key.slice(0,at);if(key.slice(at+1)!==domain||forwards[localPart])continue;forwards[localPart]=targets}const hasForwards=Object.keys(forwards).length>0;const generatePasswords=cfg.server?.generatePasswords===true;const resolved=domain?resolveMailboxesWithSkipped(cfg.mailboxes,domain,generatePasswords):{boxes:[],skipped:[]};let boxes=resolved.boxes;const interactive=canRevealSecrets();const generated=boxes.filter((box)=>box.generated);let persisted=true;if(generated.length>0){try{const{setEnv}=await import("@stacksjs/env");for(const box of generated){await setEnv(mailboxPasswordKey(box),box.password,{file:".env.production"})}logger.success(`Mail: generated and saved ${generated.length} mailbox password(s) to .env.production (encrypted)`)}catch(err){persisted=false;if(interactive){logger.warn(`Mail: could not save the generated password(s) to .env.production - they are printed below and will otherwise be regenerated next deploy: ${getErrorMessage(err)}`)}else{const unsaved=new Set(generated.map((box)=>box.address));boxes=boxes.filter((box)=>!unsaved.has(box.address));logger.warn(`Mail: could not save the generated password(s) to .env.production, and this is not an interactive terminal, so ${[...unsaved].join(", ")} were not created: ${getErrorMessage(err)}`)}}}if(resolved.skipped.length>0){logger.warn(`Mail: ${resolved.skipped.length} declared mailbox(es) were not created because no password was supplied: ${resolved.skipped.join(", ")}`);logger.info(`Set MAIL_PASSWORD_<LOCALPART> in the target environment (e.g. ${resolved.skipped[0]?.split("@")[0]?.toUpperCase().replace(/[^A-Z0-9]/g,"_")}) and run this again.`)}const declaredRecoveries=domain?resolveMailboxRecoveries(cfg.mailboxes,domain):{recoveries:[],invalid:[]};if(declaredRecoveries.invalid.length>0)logger.warn(`Mail: ignored the recovery address of ${declaredRecoveries.invalid.join(", ")} in config/email.ts: it must be a valid address outside the mailbox itself`);if(!domain&&!hasForwards)return null;const{execFileSync}=await import("node:child_process");const sshArgs=sshCliArgs(hetznerTarget(ip),{connectTimeoutSec:20});const forwardsB64=hasForwards?Buffer.from(JSON.stringify(forwards)).toString("base64"):"";const readme="Auto-forwarding rules, re-read on every message (edits take effect immediately, no restart). KEY = the delivered mailbox: the FULL address for per-domain isolated mailboxes (e.g. no-reply@app.com), or a bare local-part for legacy role mailboxes. VALUE = list of destination addresses; targets on a local domain are written straight to that mailbox Maildir, external targets are relayed. Managed by buddy deploy from config/email.ts (merge-based - hand edits to other keys are preserved).";const readmeB64=Buffer.from(readme).toString("base64");const boxesB64=boxes.length?Buffer.from(`${boxes.map((b)=>`${b.address} ${b.password} ${b.passwordPolicy}`).join(`
|
|
51
51
|
`)}
|
|
52
52
|
`).toString("base64"):"";const recoveries=declaredRecoveries.recoveries;const recoveriesB64=recoveries.length?Buffer.from(`${recoveries.map((r)=>`${r.address} ${r.recovery} ${r.policy}`).join(`
|
|
53
53
|
`)}
|
|
54
|
-
`).toString("base64"):"";const script=`set -e
|
|
54
|
+
`).toString("base64"):"";const relay=relayAccountFromConfig(cfg,domain,declaredBoxes);if(relay.problem)logger.warn(`Mail: ${relay.problem}. Nothing was changed on the mail server for it.`);const script=`set -e
|
|
55
55
|
DOMAIN=${domain?`'${domain}'`:"''"}
|
|
56
56
|
FWD_B64='${forwardsB64}'
|
|
57
57
|
README_B64='${readmeB64}'
|
|
58
58
|
BOXES_B64='${boxesB64}'
|
|
59
|
+
RELAY_ACCOUNT='${relay.account??""}'
|
|
59
60
|
RECOVERY_B64='${recoveriesB64}'
|
|
60
61
|
ENVF=/etc/mail/mail.env
|
|
61
62
|
FJSON=/opt/mail/forwards.json
|
|
@@ -81,6 +82,23 @@ if [ -n "$DOMAIN" ] && [ -f "$ENVF" ]; then
|
|
|
81
82
|
ENV_CHANGED=1 ;;
|
|
82
83
|
esac
|
|
83
84
|
fi
|
|
85
|
+
# 1b) A sending service: name its sender in SMTP_RELAY_ACCOUNTS (merged, so
|
|
86
|
+
# another service's entry stays). The mail server still asks each message
|
|
87
|
+
# for a signature by the author's own domain; this only lets the account
|
|
88
|
+
# present one.
|
|
89
|
+
if [ -n "$RELAY_ACCOUNT" ] && [ -f "$ENVF" ]; then
|
|
90
|
+
rcur=$(grep -E '^SMTP_RELAY_ACCOUNTS=' "$ENVF" | head -1 | cut -d= -f2- || true)
|
|
91
|
+
case ",$rcur," in
|
|
92
|
+
*",$RELAY_ACCOUNT,"*) : ;;
|
|
93
|
+
*) if grep -qE '^SMTP_RELAY_ACCOUNTS=' "$ENVF"; then
|
|
94
|
+
sed -i "s|^SMTP_RELAY_ACCOUNTS=.*|SMTP_RELAY_ACCOUNTS=\${rcur:+$rcur,}$RELAY_ACCOUNT|" "$ENVF"
|
|
95
|
+
else
|
|
96
|
+
echo "SMTP_RELAY_ACCOUNTS=$RELAY_ACCOUNT" >> "$ENVF"
|
|
97
|
+
fi
|
|
98
|
+
echo "RELAY:$RELAY_ACCOUNT"
|
|
99
|
+
ENV_CHANGED=1 ;;
|
|
100
|
+
esac
|
|
101
|
+
fi
|
|
84
102
|
# 2) DKIM: decide which key signs THIS domain, then register and publish that
|
|
85
103
|
# one key. Read the server's global signer first, because it wins.
|
|
86
104
|
#
|
|
@@ -467,7 +485,7 @@ EOF
|
|
|
467
485
|
systemctl daemon-reload
|
|
468
486
|
systemctl enable --now mail-health.timer >/dev/null 2>&1
|
|
469
487
|
# 6) Restart only when the startup-read env actually changed (domain or DKIM key).
|
|
470
|
-
if [ "$ENV_CHANGED" = 1 ]; then systemctl restart mail 2>/dev/null || true; echo "MAILTENANT:env-changed+restarted,forwards=$FWD_STATE"; else echo "MAILTENANT:current,forwards=$FWD_STATE"; fi`;try{const out=execFileSync("ssh",[...sshArgs,"bash","-s"],{input:script,encoding:"utf8",stdio:["pipe","pipe","pipe"]});const line=(out.match(/MAILTENANT:[^\n]*/)||[])[0]||"MAILTENANT:done";const mailHostFromOut=(out.match(/MAILHOST:([^\n]*)/)||[])[1]?.trim();const mailHost=mailHostFromOut||`mail.${domain}`;const dkimPubB64=(out.match(/DKIMPUB:([^\n]*)/)||[])[1]?.trim()||undefined;const dkimSelector=(out.match(/DKIMSEL:([^\n]*)/)||[])[1]?.trim()||undefined;const dkimGlobalKey=(out.match(/DKIMGLOBAL:([^\n]*)/)||[])[1]?.trim();if(dkimGlobalKey)logger.info(`Mail: ${domain} signs with the server's global DKIM key (${dkimGlobalKey}) — rotate that one.`);const dkimStaleKey=(out.match(/DKIMSTALE:([^\n]*)/)||[])[1]?.trim();if(dkimStaleKey)logger.warn(`Mail: ${dkimStaleKey} is an unused DKIM key left by an earlier deploy — nothing signs with it. Remove it with: rm ${dkimStaleKey}`);const madeAddrs=new Set([...out.matchAll(/MADE:([^\n]+)/g)].flatMap((m)=>m[1]?[m[1].trim()]:[]));const migratedAddrs=new Set([...out.matchAll(/MIGRATED:([^\n]+)/g)].flatMap((m)=>m[1]?[m[1].trim()]:[]));const updatedAddrs=new Set([...out.matchAll(/^UPDATED:([^\n]+)/gm)].flatMap((m)=>m[1]?[m[1].trim()]:[]));const updateFailed=[...out.matchAll(/^UPDATEFAIL:([^\n]+)/gm)].flatMap((m)=>m[1]?[m[1].trim()]:[]);const createdBoxes=boxes.filter((b)=>madeAddrs.has(b.address));const created=createdBoxes.map((b)=>({address:b.address,generated:b.generated}));logger.success(`Mail routing reconciled (${line.replace("MAILTENANT:","")})`);const failed=[...out.matchAll(/^FAIL:([^\n]+)/gm)].flatMap((m)=>m[1]?[m[1].trim()]:[]);if(failed.length)logger.warn(`Mail: the server refused ${failed.length} mailbox(es): ${failed.join(", ")}`);const forwardError=(out.match(/FWDERR:([^\n]*)/)||[])[1]?.trim();if(forwardError)logger.warn(`Mail: the forward rules were not merged: ${forwardError}`);const certHost=(out.match(/CERTHOST:([^\n]*)/)||[])[1]?.trim();if(certHost)logger.success(`Mail: ${certHost} added to the mail certificate - clients can use it as the server name`);const certError=(out.match(/CERTFAIL:([^\n]*)/)||[])[1]?.trim();if(certError)logger.warn(`Mail: could not issue a certificate for mail.${domain} (clients should use ${mailHostFromOut||"the shared mail host"}): ${certError}`);const seen=new Set([...madeAddrs,...migratedAddrs,...updatedAddrs,...updateFailed,...[...out.matchAll(/EXISTS:([^\n]+)/g)].flatMap((m)=>m[1]?[m[1].trim()]:[])]);const unaccounted=boxes.filter((b)=>!seen.has(b.address)).map((b)=>b.address);if(unaccounted.length)logger.warn(`Mail: ${unaccounted.length} declared mailbox(es) were not reconciled: ${unaccounted.join(", ")}`);reportMailboxCredentials(logger,createdBoxes,{interactive,persisted});if(updatedAddrs.size)logger.success(`Mail: set the declared password on ${updatedAddrs.size} existing mailbox(es): ${[...updatedAddrs].join(", ")}`);if(updateFailed.length)logger.warn(`Mail: could not set the declared password on ${updateFailed.length} existing mailbox(es) - they still accept the old one: ${updateFailed.join(", ")}`);if(migratedAddrs.size)logger.success(`Mail: migrated ${migratedAddrs.size} legacy mailbox username(s) to isolated full addresses`);reportRecoveryReconcile(logger,out,recoveries);return domain?{domain,mailHost,dkimPubB64,dkimSelector,created,certificateFailed:Boolean(certError)}:null}catch(err){logger.warn(`Mail routing reconcile skipped: ${getErrorMessage(err)}`);return null}}const DNS_PROVIDER_CREDENTIALS={porkbun:["PORKBUN_API_KEY","PORKBUN_SECRET_KEY"],cloudflare:["CLOUDFLARE_API_TOKEN"],godaddy:["GODADDY_API_KEY","GODADDY_API_SECRET"],route53:["AWS_ACCESS_KEY_ID (or AWS_PROFILE)"]};export function declaredDnsProvider(config){const provider=config?.tsCloud?.infrastructure?.dns?.provider??config?.infrastructure?.dns?.provider;return typeof provider==="string"&&provider?provider.toLowerCase():undefined}export function dnsProviderConfigsFromEnv(declared){const configs=[];if(process.env.PORKBUN_API_KEY&&process.env.PORKBUN_SECRET_KEY)configs.push({provider:"porkbun",apiKey:process.env.PORKBUN_API_KEY,secretKey:process.env.PORKBUN_SECRET_KEY});if(process.env.CLOUDFLARE_API_TOKEN)configs.push({provider:"cloudflare",apiToken:process.env.CLOUDFLARE_API_TOKEN});if(process.env.GODADDY_API_KEY&&process.env.GODADDY_API_SECRET)configs.push({provider:"godaddy",apiKey:process.env.GODADDY_API_KEY,apiSecret:process.env.GODADDY_API_SECRET,environment:process.env.GODADDY_ENVIRONMENT});if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_PROFILE)configs.push({provider:"route53"});if(!declared)return configs;return configs.filter((config)=>config.provider===declared)}export function declaredDnsProviderProblem(declared,configs){if(!declared||configs.length>0)return;const needed=DNS_PROVIDER_CREDENTIALS[declared];if(!needed)return`config/cloud.ts declares the DNS provider '${declared}', which is not one this deploy knows how to drive (${Object.keys(DNS_PROVIDER_CREDENTIALS).join(", ")}).`;return`config/cloud.ts declares '${declared}' as the DNS provider for this project, but ${needed.join(" and ")} ${needed.length>1?"are":"is"} not set in this environment. Set ${needed.length>1?"them":"it"} in .env.production (\`buddy env:set\`) so the records land at the registrar that actually administers the zone. Refusing to try another provider: writing DNS into the wrong zone is not better than writing none.`}async function resolveZoneDnsProvider(domain,providerConfigs,logger){if(providerConfigs.length===0)return;const{createDnsProvider,detectDnsProvider}=await import("@stacksjs/ts-cloud");const provider=await detectDnsProvider(domain,providerConfigs).catch((err)=>{logger.warn(` DNS: ignoring a configured provider for ${domain} - its credentials were rejected (${err?.message||err})`);return});if(provider)return provider;let nameservers=[];try{const{resolveNs}=await import("node:dns/promises");nameservers=await resolveNs(domain)}catch{}const providerName=dnsProviderNameFromNameservers(nameservers);const providerConfig=providerConfigs.find((config)=>config.provider===providerName);return providerConfig?createDnsProvider(providerConfig):undefined}export function resolveDmarcPolicy(policy){return policy==="none"||policy==="quarantine"||policy==="reject"?policy:"quarantine"}export function resolvePostmasterRecord(value){if(typeof value!=="string")return;const token=value.trim().replace(/^"|"$/g,"").replace(/^google-site-verification=/i,"");return/^[\w-]{20,}$/.test(token)?`google-site-verification=${token}`:undefined}export function postmasterHint(domain,postmaster){if(postmaster===false)return;if(postmaster&&typeof postmaster==="object"&&resolvePostmasterRecord(postmaster.google))return;return`Gmail Postmaster Tools: add ${domain} at https://postmaster.google.com/v2/u/0/add_domain, then set email.server.postmaster.google to the TXT value it shows; the next deploy publishes it (false silences this).`}export function zoneFqdn(name,zone){const apex=zone.replace(/\.$/,"").toLowerCase();const n=String(name??"").replace(/\.$/,"").toLowerCase();if(!n||n==="@")return apex;return n===apex||n.endsWith(`.${apex}`)?n:`${n}.${apex}`}export function selectRecordsAt(records,fqdn,type,zone){const target=zoneFqdn(fqdn,zone);return records.filter((r)=>String(r.type).toUpperCase()===type.toUpperCase()&&zoneFqdn(r.name,zone)===target)}export function findMailDnsAnomalies(records,expectations,zone){const problems=[];for(const expectation of expectations){const at=selectRecordsAt(records,expectation.fqdn,expectation.type,zone);const ours=expectation.owns?at.filter((record)=>expectation.owns(txtContent(record))):at;if(ours.length===0)problems.push(`${expectation.label}: nothing published at ${expectation.fqdn}`);else if(ours.length>1)problems.push(`${expectation.label}: ${ours.length} records at ${expectation.fqdn}, expected 1 - receivers treat a duplicated ${expectation.type} here as unconfigured, so remove the stale one`)}return problems}export function txtContent(record){return String(record.content??record.value??"").replace(/^"|"$/g,"")}export function planTxtReplacement(existing,content,owns){const ours=existing.filter((record)=>owns(txtContent(record)));if(ours.length===1&&txtContent(ours[0])===content)return{remove:[],create:false};return{remove:ours,create:true}}export async function reconcileMailDns(res,ip,logger){const{domain,dkimPubB64}=res;let{mailHost}=res;const dkimName=`${res.dkimSelector||"mail"}._domainkey`;try{const dns=await import("node:dns");const own=`mail.${domain}`;if(own!==mailHost&&(await dns.promises.resolve4(own)).includes(ip))mailHost=own}catch{}const spf=`v=spf1 ip4:${ip} ~all`;const cfg=emailConfig||{};const firstBox=resolveMailboxes(cfg.mailboxes,domain)[0]?.address;const fromAddress=typeof cfg.from?.address==="string"&&cfg.from.address.includes("@")?cfg.from.address:undefined;const dmarcCfg=cfg.server?.dmarc||{};const rua=dmarcCfg.reportTo||fromAddress||firstBox||`chris@${domain}`;const dmarc=`v=DMARC1; p=${resolveDmarcPolicy(dmarcCfg.policy)}; rua=mailto:${rua}`;const dkim=dkimPubB64?`v=DKIM1; k=rsa; p=${dkimPubB64}`:undefined;const postmasterCfg=cfg.server?.postmaster;const postmaster=postmasterCfg?resolvePostmasterRecord(postmasterCfg.google):undefined;if(postmasterCfg&&postmasterCfg.google&&!postmaster)logger.warn(` Mail DNS: email.server.postmaster.google is not a Postmaster Tools token, so it was not published. Copy the TXT value Postmaster Tools shows for ${domain}.`);const envFile=envFileForEnvironment(process.env.APP_ENV||"production");const byHand=async(reason,knownProvider)=>{const ns=knownProvider?{nameservers:[]}:await resolveZoneNameservers(domain).catch(()=>({nameservers:[]}));const provider=knownProvider??dnsProviderNameFromNameservers(ns.nameservers);logger.warn(`Mail DNS NOT published for ${domain}: ${reason}. Until these records exist, mail from ${domain} fails SPF, DKIM and DMARC and lands in spam or bounces.`);logger.warn(` Fix: ${dnsCredentialFix(provider,envFile,ns.nameservers)}`);logger.warn(` Or add these records by hand at the DNS host:`);logger.warn(` MX @ 10 ${mailHost}`);logger.warn(` TXT @ ${spf}`);if(dkim)logger.warn(` TXT ${dkimName.padEnd(17)}${dkim}`);logger.warn(` TXT _dmarc ${dmarc}`);if(postmaster)logger.warn(` TXT @ ${postmaster}`);logger.warn(` A mail ${ip}`)};const declared=declaredDnsProvider(await loadTsCloudConfig(process.env.APP_ENV||"production").catch(()=>{return}));const providerConfigs=dnsProviderConfigsFromEnv(declared);const declaredProblem=declaredDnsProviderProblem(declared,providerConfigs);if(declaredProblem){logger.warn(` DNS: ${declaredProblem}`);return byHand(`the declared provider '${declared}' has no credentials in this environment`,declared)}if(providerConfigs.length===0)return byHand("no DNS provider credentials are configured");const provider=await resolveZoneDnsProvider(domain,providerConfigs,logger);if(!provider)return byHand(`no configured DNS provider administers this zone`);const apex=domain.toLowerCase();const dkimFqdn=`${dkimName}.${domain}`;const dmarcFqdn=`_dmarc.${domain}`;const mailFqdn=`mail.${domain}`;const recordsAt=async(fqdn,type)=>{const res=await provider.listRecords(domain);return selectRecordsAt(res?.success?res.records||[]:[],fqdn,type,domain)};const replaceTxt=async(fqdn,content,owns)=>{const existing=await recordsAt(fqdn,"TXT");const{remove,create}=planTxtReplacement(existing,content,owns);if(!create)return;for(const record of remove){const removed=await provider.deleteRecord(domain,{...record,name:fqdn,type:"TXT"});if(removed&&removed.success===false)throw new Error(`TXT ${fqdn}: could not remove the record being replaced (${removed.message||"provider refused the delete"})`)}const created=await provider.createRecord(domain,{name:fqdn,type:"TXT",content,ttl:600});if(!created?.success)throw new Error(`TXT ${fqdn}: ${created?.message||"provider rejected the record"}`)};try{const mxRecords=await recordsAt(apex,"MX");const staleMx=mxRecords.filter((r)=>String(r.content??r.value??"").replace(/\.$/,"").toLowerCase()!==mailHost.toLowerCase());for(const record of staleMx){logger.warn(` Mail DNS: replacing an existing MX for ${domain} → ${record.content??record.value}`);await provider.deleteRecord(domain,{...record,name:apex,type:"MX"})}if(mxRecords.length===staleMx.length){const created=await provider.createRecord(domain,{name:apex,type:"MX",content:mailHost,ttl:600,priority:10});if(!created?.success)throw new Error(`MX ${domain}: ${created?.message||"provider rejected the record"}`)}await replaceTxt(apex,spf,(existing)=>existing.toLowerCase().startsWith("v=spf1"));if(dkim)await replaceTxt(dkimFqdn,dkim,()=>true);await replaceTxt(dmarcFqdn,dmarc,(existing)=>existing.toLowerCase().startsWith("v=dmarc1"));if(postmaster)await replaceTxt(apex,postmaster,(existing)=>existing===postmaster);const mailA=await provider.upsertRecord(domain,{name:mailFqdn,type:"A",content:ip,ttl:600});if(!mailA?.success)throw new Error(`A ${mailFqdn}: ${mailA?.message||"provider rejected the record"}`);const verifyRes=await provider.listRecords(domain);const anomalies=verifyRes?.success?findMailDnsAnomalies(verifyRes.records||[],[{label:"MX",fqdn:apex,type:"MX"},{label:"SPF",fqdn:apex,type:"TXT",owns:(content)=>content.toLowerCase().startsWith("v=spf1")},...dkim?[{label:"DKIM",fqdn:dkimFqdn,type:"TXT"}]:[],{label:"DMARC",fqdn:dmarcFqdn,type:"TXT",owns:(content)=>content.toLowerCase().startsWith("v=dmarc1")},...postmaster?[{label:"Postmaster Tools",fqdn:apex,type:"TXT",owns:(content)=>content===postmaster}]:[]],domain):[];for(const anomaly of anomalies)logger.warn(` Mail DNS: ${anomaly}`);logger.success(`Mail DNS published for ${domain} via ${provider.name} (MX→${mailHost}, SPF, DKIM at ${dkimName}, DMARC, ${postmaster?"Postmaster Tools, ":""}${mailFqdn}→${ip})`);const hint=postmasterHint(domain,postmasterCfg);if(hint)logger.info(` ${hint}`)}catch(err){logger.warn(`Mail DNS reconcile skipped for ${domain}: ${getErrorMessage(err)}`)}}export function configDnsDomains(sites){const domains=new Set;for(const site of Object.values(sites)){if(!site?.redirect&&site?.domain&&typeof site.domain==="string")domains.add(site.domain.replace(/^www\./,""))}const all=[...domains];return all.filter((domain)=>!all.some((other)=>other!==domain&&domain.endsWith(`.${other}`)))}async function reconcileCloudflareCdnForDeploy(tsCloudConfig,ip,ipv6,logger){let resolveCloudflareCdnPlan;let reconcileCloudflareCdn;let CloudflareProvider;let normalizePublicIpv6;try{({resolveCloudflareCdnPlan,reconcileCloudflareCdn,CloudflareProvider,normalizePublicIpv6}=await import("@stacksjs/ts-cloud"))}catch{return}if(typeof resolveCloudflareCdnPlan!=="function"||typeof reconcileCloudflareCdn!=="function"){if(tsCloudConfig?.infrastructure?.compute?.proxy?.cdn?.provider==="cloudflare")logger.warn("Cloudflare CDN: installed @stacksjs/ts-cloud is too old to manage it — upgrade to ^0.9.4.");return}const{plan,errors}=resolveCloudflareCdnPlan(tsCloudConfig);for(const error of errors)logger.warn(`Cloudflare CDN: ${error}`);if(!plan)return;if(!ip){logger.warn("Cloudflare CDN: no box IP resolved — skipping.");return}logger.info(`Cloudflare CDN: reconciling ${plan.hosts.length} host(s) on ${plan.zone}...`);try{const provider=new CloudflareProvider(plan.apiToken,{zoneId:plan.zoneId,accountId:plan.accountId});const report=await reconcileCloudflareCdn({provider,zone:plan.zone,hosts:plan.hosts,ipv4:ip,ipv6:typeof normalizePublicIpv6==="function"?normalizePublicIpv6(ipv6):ipv6,proxied:plan.proxied,settings:plan.settings,cache:plan.cache,originGuard:plan.originGuard,purge:plan.purge,skipOriginProbe:plan.skipOriginProbe,edgeWait:plan.edgeWaitMs>0?{timeoutMs:plan.edgeWaitMs,whilePending:zoneDelegatedThisDeploy,onProgress:(message)=>logger.info(` ${message}`)}:undefined});for(const record of report.records)logger.success(` ${record.host} ${record.type} → ${record.content}${record.proxied?" (proxied)":" (DNS-only)"}`);for(const setting of report.settingsChanged)logger.info(` ${setting.id}: ${JSON.stringify(setting.from)} → ${JSON.stringify(setting.to)}`);if(report.cacheRules>0)logger.success(` ${report.cacheRules} cache rule(s) applied`);if(report.originGuard)logger.success(" origin guard header applied");if(report.purged)logger.success(" edge cache purged");for(const deferred of report.deferredProxy||[])logger.warn(` ${deferred.host} left DNS-only: ${deferred.reason}. The next deploy proxies it once the certificate is there.`);for(const warning of report.warnings)logger.warn(` ${warning}`)}catch(err){logger.warn(`Cloudflare CDN: ${err?.message||err}`)}}async function reconcileR2ForDeploy(tsCloudConfig,logger){const buckets=tsCloudConfig?.infrastructure?.r2?.buckets;if(!buckets||Object.keys(buckets).length===0)return;let reconcileR2Buckets;try{({reconcileR2Buckets}=await import("@stacksjs/ts-cloud"))}catch{return}if(typeof reconcileR2Buckets!=="function"){logger.warn("R2: installed @stacksjs/ts-cloud is too old to manage buckets. Upgrade it to provision infrastructure.r2.");return}const apiToken=process.env.CLOUDFLARE_API_TOKEN;const accountId=process.env.CLOUDFLARE_ACCOUNT_ID;if(!apiToken||!accountId){logger.warn("R2: CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID are both needed to provision buckets. Skipping.");return}logger.info(`R2: reconciling ${Object.keys(buckets).length} bucket(s)...`);try{const summary=await reconcileR2Buckets(tsCloudConfig,{apiToken,accountId,zoneId:process.env.CLOUDFLARE_ZONE_ID||undefined,log:(message)=>logger.info(` ${message}`)});for(const bucket of summary?.buckets??[]){const changes=bucket.changes?.length?bucket.changes.join(", "):"in sync";logger.success(` ${bucket.name}: ${changes}`);for(const domain of bucket.domains??[])logger.success(` https://${domain.domain}${domain.status?` (${domain.status})`:""}`)}for(const warning of summary?.warnings??[])logger.warn(` ${warning}`)}catch(err){logger.warn(`R2: ${err?.message||err}`)}}async function reconcileWorkersForDeploy(tsCloudConfig,logger){const workers=tsCloudConfig?.infrastructure?.workers;if(!workers||Object.keys(workers).length===0)return;let reconcileCloudflareWorkers;try{({reconcileCloudflareWorkers}=await import("@stacksjs/ts-cloud"))}catch{return}if(typeof reconcileCloudflareWorkers!=="function"){logger.warn("Workers: installed @stacksjs/ts-cloud is too old to deploy them. Upgrade it to deploy infrastructure.workers.");return}const apiToken=process.env.CLOUDFLARE_API_TOKEN;const accountId=process.env.CLOUDFLARE_ACCOUNT_ID;if(!apiToken||!accountId){logger.warn("Workers: CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID are both needed to deploy them. Skipping.");return}logger.info(`Workers: reconciling ${Object.keys(workers).length} worker(s)...`);try{const summary=await reconcileCloudflareWorkers(tsCloudConfig,{apiToken,accountId,projectRoot:process.cwd(),zoneId:process.env.CLOUDFLARE_ZONE_ID||undefined,log:(message)=>logger.info(` ${message}`)});for(const worker of summary?.workers??[]){const changes=worker.changes?.length?worker.changes.join(", "):"in sync";logger.success(` ${worker.name}: ${changes}`);for(const domain of worker.domains??[])logger.success(` https://${domain.domain}${domain.status?` (${domain.status})`:""}`)}for(const warning of summary?.warnings??[])logger.warn(` ${warning}`)}catch(err){logger.warn(`Workers: ${err?.message||err}`)}}export function dnsProviderNameFromNameservers(nameservers){const normalized=nameservers.map((name)=>name.toLowerCase().replace(/\.$/,""));if(normalized.some((name)=>name.endsWith(".porkbun.com")))return"porkbun";if(normalized.some((name)=>name.endsWith(".ns.cloudflare.com")))return"cloudflare";if(normalized.some((name)=>/(^|\.)awsdns-\d+\.(?:com|net|org|co\.uk)$/.test(name)))return"route53";if(normalized.some((name)=>name.endsWith(".domaincontrol.com")))return"godaddy";return null}async function reconcileCommsHqSendingDomain(deployEnv,tsCloudConfig,logger){const key=deployEnv.COMMSHQ_KEY;if(!key)return;try{const{setUpSendingDomainForApp}=await import("../commshq-domain-run");logger.info("CommsHQ: checking the sending domain...");const outcome=await setUpSendingDomainForApp({url:deployEnv.COMMSHQ_URL||"https://commshq.org",key,mailFrom:deployEnv.MAIL_FROM_ADDRESS,appUrl:deployEnv.APP_URL,zone:tsCloudConfig?.infrastructure?.dns?.domain,print:(line)=>logger.info(line)});if(outcome.status==="failed")logger.warn(`CommsHQ: the sending domain was not set up: ${outcome.detail}`)}catch(err){logger.warn(`CommsHQ: sending domain setup failed: ${err instanceof Error?err.message:String(err)}`)}}async function reconcileConfigDns(sites,logger){const projectDnsConfig=await loadProjectDnsConfig(dnsConfig);const declared=["a","aaaa","cname","mx","txt"].reduce((total,key)=>total+(Array.isArray(projectDnsConfig?.[key])?projectDnsConfig[key].length:0),0);if(declared===0)return;for(const domain of configDnsDomains(sites)){try{const result=await syncDnsConfig(domain,projectDnsConfig);if(!result.provider)continue;if(result.created||result.failed)logger.info(`DNS (config/dns.ts) ${domain}: ${result.created} created, ${result.kept} kept${result.failed?`, ${result.failed} failed`:""}`);for(const failure of result.failures)logger.warn(` ${failure.record.type} ${failure.record.name} → ${failure.record.content}: ${failure.reason}`);for(const skipped of result.skipped)logger.info(` skipped ${skipped.record.type} ${skipped.record.name}: ${skipped.reason}`)}catch(err){logger.warn(`DNS (config/dns.ts) reconcile for ${domain} failed: ${err instanceof Error?err.message:String(err)}`)}}}export async function syncRoutesAfterDeploy(deployEnv,logger){const key=deployEnv.STATUSHQ_KEY||process.env.STATUSHQ_KEY;if(!key)return;try{const{config}=await import("@stacksjs/config");const{collectRouteManifest,readProductionRouteContext}=await import("../hq-routes");const{runHqRouteSync}=await import("../hq");const services=config.services??{};const context=await readProductionRouteContext(deployEnv);const baseUrl=context.baseUrl;await runHqRouteSync({...services,statushq:{...services.statushq,url:deployEnv.STATUSHQ_URL||services.statushq?.url||"https://statushq.org"}},{name:String(deployEnv.APP_NAME||config.app?.name||"app")},{baseUrl,manifest:await collectRouteManifest(context.env)},{fetch:(input,init)=>fetch(input,init),print:(line)=>logger.info(line)},key)}catch(error){logger.warn(`StatusHQ: routes not synced (${error instanceof Error?error.message:String(error)}). Run \`buddy hq:sync\` to try again.`)}}let zoneDelegatedThisDeploy=false;export async function delegateDeclaredZone(config,logger){const dns=config?.tsCloud?.infrastructure?.dns??config?.infrastructure?.dns;zoneDelegatedThisDeploy=false;if(!dns?.registrar)return;try{const{applyDeclaredZoneSettings,delegateZoneFromConfig,describeDelegation,describeZoneSettings}=await import("@stacksjs/ts-cloud");const result=await delegateZoneFromConfig(dns);zoneDelegatedThisDeploy=result.status==="delegated"||result.status==="already-delegated";for(const line of describeDelegation(result))logger.info(line);if(result.status==="blocked")logger.warn("DNS: delegation did not complete; the domain still resolves through its registrar.");const settings=await applyDeclaredZoneSettings(dns);for(const line of describeZoneSettings(settings))logger.info(line);if(settings.status!=="skipped"&&settings.failed.length>0)logger.warn(`DNS: ${settings.failed.length} zone setting(s) could not be applied; the zone is serving with its previous values.`)}catch(error){logger.warn(`DNS: zone reconciliation could not run: ${error instanceof Error?error.message:String(error)}`)}}export async function reconcileHetznerDns(sites,ip,logger,ipv6,autoWww){const published=[];const{gatewayHostnames}=await import("@stacksjs/ts-cloud");const hostnames=gatewayHostnames(sites,{autoWww});const byBase=new Map;for(const fqdn of hostnames){const base=fqdn.replace(/^(?:www|\*)\./,"");const group=byBase.get(base)??new Set;group.add(fqdn);byBase.set(base,group)}if(byBase.size===0)return published;const tsCloudConfig=await loadTsCloudConfig(process.env.APP_ENV||"production").catch(()=>{return});await delegateDeclaredZone(tsCloudConfig,logger);const declared=declaredDnsProvider(tsCloudConfig);const providerConfigs=dnsProviderConfigsFromEnv(declared);const declaredProblem=declaredDnsProviderProblem(declared,providerConfigs);if(declaredProblem)logger.warn(`DNS: ${declaredProblem}`);if(providerConfigs.length===0){if(!declaredProblem)logger.warn("DNS: no DNS provider credentials found (PORKBUN_API_KEY/…); skipping DNS reconciliation.");for(const fqdn of hostnames)logger.info(` Point manually: A ${fqdn} → ${ip}`);return published}const{reconcileAddressRecords}=await import("@stacksjs/ts-cloud");logger.info("Reconciling DNS records...");const resolveA=async(fqdn)=>{try{const{resolve4}=await import("node:dns/promises");return await resolve4(fqdn)}catch{return[]}};for(const[domain,group]of byBase){const fqdns=[...group].sort();try{const provider=await resolveZoneDnsProvider(domain,providerConfigs,logger);if(!provider){for(const fqdn of fqdns){const current=await resolveA(fqdn);if(current.includes(ip))logger.success(` DNS: ${fqdn} → ${ip} (externally managed, already correct)`);else if(current.length===0)logger.warn(` DNS: ${fqdn} does not resolve and no configured provider manages ${domain} - create it manually: A ${fqdn} → ${ip}`);else logger.warn(` DNS: ${fqdn} resolves to ${current.join(", ")} but this deploy targets ${ip}, and no configured provider manages ${domain} - update it manually: A ${fqdn} → ${ip}`)}continue}for(const fqdn of fqdns){const report=await reconcileAddressRecords({provider,zone:domain,fqdn,ipv4:ip,ipv6});for(const record of report.published){logger.success(` DNS: ${record.fqdn} → ${record.content} (${provider.name})`);published.push(record.fqdn)}for(const warning of report.warnings)logger.warn(` DNS: ${warning}`)}}catch(err){logger.warn(` DNS: ${domain} reconciliation failed: ${err?.message||err}`)}}return published}async function runPreviewCommand(name,options,action){const base=resolveDeploymentEnvironment({option:options.base});if(action==="deploy")await assertPublicationAllowed({cwd:p.projectPath(),channel:"preview"});const envFile=".env.preview";if(action==="deploy"&&!existsSync(p.projectPath(envFile))){log.error(`Previews read their secrets from ${envFile} only, and this project has none.`);log.info(`Create it with its own database, mail and API credentials (never production's): buddy env:set --file ${envFile} APP_KEY ...`);process.exit(ExitCode.FatalError)}if(existsSync(p.projectPath(envFile))){const{loadEnv}=await import("@stacksjs/env");loadEnv({path:envFile,env:"preview",keysFile:".env.keys",overload:true,quiet:true})}const appConfig=await loadTsCloudConfig(base);if(!appConfig){log.error("Previews need config/cloud.ts.");process.exit(ExitCode.FatalError)}const provider=resolveProvider(appConfig);if(!isSshPipelineProvider(provider)){log.error(`Previews run as a tenant on the app's box, which the '${provider}' provider does not have. They work with cloud.provider 'hetzner' or 'ssh'.`);process.exit(ExitCode.FatalError)}let target;try{target=previewTarget(appConfig,name,previewDomain(appConfig,process.env))}catch(error){log.error(getErrorMessage(error));process.exit(ExitCode.InvalidArgument)}const sshTarget=provider==="ssh"?resolveSshTarget(appConfig):null;const lookup=provider==="ssh"?null:await resolveAttachTargetBox(target.owner,base,appConfig);const host=sshTarget?.host??lookup?.box?.publicIp;if(!host){log.error(provider==="ssh"?"No SSH host configured for this project.":describeAttachLookupFailure(target.owner,base,lookup?.failure));process.exit(ExitCode.FatalError)}const remoteTarget=sshTarget?{...sshTarget,host}:hetznerTarget(host);const{sshExecOrThrow}=await import("@stacksjs/ts-cloud");const runRemote=(script)=>{const encoded=Buffer.from(script).toString("base64");const privileged=remoteTarget.user==="root"?"bash":"sudo -n bash";return sshExecOrThrow(host,`echo ${encoded} | base64 -d | ${privileged}`,remoteExecOptions(remoteTarget,15))};if(action==="remove"){await removePreview(target,base,runRemote);return}const{buildHostSitePortsScript,occupiedHostPorts,parseHostSiteFragments}=await import("@stacksjs/ts-cloud");const owners=occupiedHostPorts(parseHostSiteFragments(await runRemote(buildHostSitePortsScript())));const port=previewPort(owners,target.slug,Number(appConfig.sites?.[target.site]?.port)||3000);log.info(`Deploying preview ${target.slug} to ${target.url} (port ${port} on ${host})`);await deployOverSsh(derivePreviewConfig(appConfig,target,port),base,{verbose:options.verbose===true,yes:true},envFile);log.success(`Preview deployed: ${target.url}`);if(process.env.GITHUB_OUTPUT)writeFileSync(process.env.GITHUB_OUTPUT,`url=${target.url}
|
|
488
|
+
if [ "$ENV_CHANGED" = 1 ]; then systemctl restart mail 2>/dev/null || true; echo "MAILTENANT:env-changed+restarted,forwards=$FWD_STATE"; else echo "MAILTENANT:current,forwards=$FWD_STATE"; fi`;try{const out=execFileSync("ssh",[...sshArgs,"bash","-s"],{input:script,encoding:"utf8",stdio:["pipe","pipe","pipe"]});const line=(out.match(/MAILTENANT:[^\n]*/)||[])[0]||"MAILTENANT:done";const mailHostFromOut=(out.match(/MAILHOST:([^\n]*)/)||[])[1]?.trim();const mailHost=mailHostFromOut||`mail.${domain}`;const dkimPubB64=(out.match(/DKIMPUB:([^\n]*)/)||[])[1]?.trim()||undefined;const dkimSelector=(out.match(/DKIMSEL:([^\n]*)/)||[])[1]?.trim()||undefined;const dkimGlobalKey=(out.match(/DKIMGLOBAL:([^\n]*)/)||[])[1]?.trim();if(dkimGlobalKey)logger.info(`Mail: ${domain} signs with the server's global DKIM key (${dkimGlobalKey}) — rotate that one.`);const dkimStaleKey=(out.match(/DKIMSTALE:([^\n]*)/)||[])[1]?.trim();if(dkimStaleKey)logger.warn(`Mail: ${dkimStaleKey} is an unused DKIM key left by an earlier deploy — nothing signs with it. Remove it with: rm ${dkimStaleKey}`);const madeAddrs=new Set([...out.matchAll(/MADE:([^\n]+)/g)].flatMap((m)=>m[1]?[m[1].trim()]:[]));const migratedAddrs=new Set([...out.matchAll(/MIGRATED:([^\n]+)/g)].flatMap((m)=>m[1]?[m[1].trim()]:[]));const updatedAddrs=new Set([...out.matchAll(/^UPDATED:([^\n]+)/gm)].flatMap((m)=>m[1]?[m[1].trim()]:[]));const updateFailed=[...out.matchAll(/^UPDATEFAIL:([^\n]+)/gm)].flatMap((m)=>m[1]?[m[1].trim()]:[]);const createdBoxes=boxes.filter((b)=>madeAddrs.has(b.address));const created=createdBoxes.map((b)=>({address:b.address,generated:b.generated}));logger.success(`Mail routing reconciled (${line.replace("MAILTENANT:","")})`);const failed=[...out.matchAll(/^FAIL:([^\n]+)/gm)].flatMap((m)=>m[1]?[m[1].trim()]:[]);if(failed.length)logger.warn(`Mail: the server refused ${failed.length} mailbox(es): ${failed.join(", ")}`);const forwardError=(out.match(/FWDERR:([^\n]*)/)||[])[1]?.trim();if(forwardError)logger.warn(`Mail: the forward rules were not merged: ${forwardError}`);const relayNamed=(out.match(/RELAY:([^\n]*)/)||[])[1]?.trim();if(relayNamed)logger.success(`Mail: ${relayNamed} may now relay mail that a customer's own domain has signed`);const certHost=(out.match(/CERTHOST:([^\n]*)/)||[])[1]?.trim();if(certHost)logger.success(`Mail: ${certHost} added to the mail certificate - clients can use it as the server name`);const certError=(out.match(/CERTFAIL:([^\n]*)/)||[])[1]?.trim();if(certError)logger.warn(`Mail: could not issue a certificate for mail.${domain} (clients should use ${mailHostFromOut||"the shared mail host"}): ${certError}`);const seen=new Set([...madeAddrs,...migratedAddrs,...updatedAddrs,...updateFailed,...[...out.matchAll(/EXISTS:([^\n]+)/g)].flatMap((m)=>m[1]?[m[1].trim()]:[])]);const unaccounted=boxes.filter((b)=>!seen.has(b.address)).map((b)=>b.address);if(unaccounted.length)logger.warn(`Mail: ${unaccounted.length} declared mailbox(es) were not reconciled: ${unaccounted.join(", ")}`);reportMailboxCredentials(logger,createdBoxes,{interactive,persisted});if(updatedAddrs.size)logger.success(`Mail: set the declared password on ${updatedAddrs.size} existing mailbox(es): ${[...updatedAddrs].join(", ")}`);if(updateFailed.length)logger.warn(`Mail: could not set the declared password on ${updateFailed.length} existing mailbox(es) - they still accept the old one: ${updateFailed.join(", ")}`);if(migratedAddrs.size)logger.success(`Mail: migrated ${migratedAddrs.size} legacy mailbox username(s) to isolated full addresses`);reportRecoveryReconcile(logger,out,recoveries);return domain?{domain,mailHost,dkimPubB64,dkimSelector,created,certificateFailed:Boolean(certError)}:null}catch(err){logger.warn(`Mail routing reconcile skipped: ${getErrorMessage(err)}`);return null}}const DNS_PROVIDER_CREDENTIALS={porkbun:["PORKBUN_API_KEY","PORKBUN_SECRET_KEY"],cloudflare:["CLOUDFLARE_API_TOKEN"],godaddy:["GODADDY_API_KEY","GODADDY_API_SECRET"],route53:["AWS_ACCESS_KEY_ID (or AWS_PROFILE)"]};export function declaredDnsProvider(config){const provider=config?.tsCloud?.infrastructure?.dns?.provider??config?.infrastructure?.dns?.provider;return typeof provider==="string"&&provider?provider.toLowerCase():undefined}export function dnsProviderConfigsFromEnv(declared){const configs=[];if(process.env.PORKBUN_API_KEY&&process.env.PORKBUN_SECRET_KEY)configs.push({provider:"porkbun",apiKey:process.env.PORKBUN_API_KEY,secretKey:process.env.PORKBUN_SECRET_KEY});if(process.env.CLOUDFLARE_API_TOKEN)configs.push({provider:"cloudflare",apiToken:process.env.CLOUDFLARE_API_TOKEN});if(process.env.GODADDY_API_KEY&&process.env.GODADDY_API_SECRET)configs.push({provider:"godaddy",apiKey:process.env.GODADDY_API_KEY,apiSecret:process.env.GODADDY_API_SECRET,environment:process.env.GODADDY_ENVIRONMENT});if(process.env.AWS_ACCESS_KEY_ID||process.env.AWS_PROFILE)configs.push({provider:"route53"});if(!declared)return configs;return configs.filter((config)=>config.provider===declared)}export function declaredDnsProviderProblem(declared,configs){if(!declared||configs.length>0)return;const needed=DNS_PROVIDER_CREDENTIALS[declared];if(!needed)return`config/cloud.ts declares the DNS provider '${declared}', which is not one this deploy knows how to drive (${Object.keys(DNS_PROVIDER_CREDENTIALS).join(", ")}).`;return`config/cloud.ts declares '${declared}' as the DNS provider for this project, but ${needed.join(" and ")} ${needed.length>1?"are":"is"} not set in this environment. Set ${needed.length>1?"them":"it"} in .env.production (\`buddy env:set\`) so the records land at the registrar that actually administers the zone. Refusing to try another provider: writing DNS into the wrong zone is not better than writing none.`}async function resolveZoneDnsProvider(domain,providerConfigs,logger){if(providerConfigs.length===0)return;const{createDnsProvider,detectDnsProvider}=await import("@stacksjs/ts-cloud");const provider=await detectDnsProvider(domain,providerConfigs).catch((err)=>{logger.warn(` DNS: ignoring a configured provider for ${domain} - its credentials were rejected (${err?.message||err})`);return});if(provider)return provider;let nameservers=[];try{const{resolveNs}=await import("node:dns/promises");nameservers=await resolveNs(domain)}catch{}const providerName=dnsProviderNameFromNameservers(nameservers);const providerConfig=providerConfigs.find((config)=>config.provider===providerName);return providerConfig?createDnsProvider(providerConfig):undefined}export function resolveDmarcPolicy(policy){return policy==="none"||policy==="quarantine"||policy==="reject"?policy:"quarantine"}export function resolvePostmasterRecord(value){if(typeof value!=="string")return;const token=value.trim().replace(/^"|"$/g,"").replace(/^google-site-verification=/i,"");return/^[\w-]{20,}$/.test(token)?`google-site-verification=${token}`:undefined}export function postmasterHint(domain,postmaster){if(postmaster===false)return;if(postmaster&&typeof postmaster==="object"&&resolvePostmasterRecord(postmaster.google))return;return`Gmail Postmaster Tools: add ${domain} at https://postmaster.google.com/v2/u/0/add_domain, then set email.server.postmaster.google to the TXT value it shows; the next deploy publishes it (false silences this).`}export function zoneFqdn(name,zone){const apex=zone.replace(/\.$/,"").toLowerCase();const n=String(name??"").replace(/\.$/,"").toLowerCase();if(!n||n==="@")return apex;return n===apex||n.endsWith(`.${apex}`)?n:`${n}.${apex}`}export function selectRecordsAt(records,fqdn,type,zone){const target=zoneFqdn(fqdn,zone);return records.filter((r)=>String(r.type).toUpperCase()===type.toUpperCase()&&zoneFqdn(r.name,zone)===target)}export function findMailDnsAnomalies(records,expectations,zone){const problems=[];for(const expectation of expectations){const at=selectRecordsAt(records,expectation.fqdn,expectation.type,zone);const ours=expectation.owns?at.filter((record)=>expectation.owns(txtContent(record))):at;if(ours.length===0)problems.push(`${expectation.label}: nothing published at ${expectation.fqdn}`);else if(ours.length>1)problems.push(`${expectation.label}: ${ours.length} records at ${expectation.fqdn}, expected 1 - receivers treat a duplicated ${expectation.type} here as unconfigured, so remove the stale one`)}return problems}export function txtContent(record){return String(record.content??record.value??"").replace(/^"|"$/g,"")}export function planTxtReplacement(existing,content,owns){const ours=existing.filter((record)=>owns(txtContent(record)));if(ours.length===1&&txtContent(ours[0])===content)return{remove:[],create:false};return{remove:ours,create:true}}export async function reconcileMailDns(res,ip,logger){const{domain,dkimPubB64}=res;let{mailHost}=res;const dkimName=`${res.dkimSelector||"mail"}._domainkey`;try{const dns=await import("node:dns");const own=`mail.${domain}`;if(own!==mailHost&&(await dns.promises.resolve4(own)).includes(ip))mailHost=own}catch{}const spf=`v=spf1 ip4:${ip} ~all`;const cfg=emailConfig||{};const firstBox=resolveMailboxes(cfg.mailboxes,domain)[0]?.address;const fromAddress=typeof cfg.from?.address==="string"&&cfg.from.address.includes("@")?cfg.from.address:undefined;const dmarcCfg=cfg.server?.dmarc||{};const rua=dmarcCfg.reportTo||fromAddress||firstBox||`chris@${domain}`;const dmarc=`v=DMARC1; p=${resolveDmarcPolicy(dmarcCfg.policy)}; rua=mailto:${rua}`;const dkim=dkimPubB64?`v=DKIM1; k=rsa; p=${dkimPubB64}`:undefined;const postmasterCfg=cfg.server?.postmaster;const postmaster=postmasterCfg?resolvePostmasterRecord(postmasterCfg.google):undefined;if(postmasterCfg&&postmasterCfg.google&&!postmaster)logger.warn(` Mail DNS: email.server.postmaster.google is not a Postmaster Tools token, so it was not published. Copy the TXT value Postmaster Tools shows for ${domain}.`);const envFile=envFileForEnvironment(process.env.APP_ENV||"production");const byHand=async(reason,knownProvider)=>{const ns=knownProvider?{nameservers:[]}:await resolveZoneNameservers(domain).catch(()=>({nameservers:[]}));const provider=knownProvider??dnsProviderNameFromNameservers(ns.nameservers);logger.warn(`Mail DNS NOT published for ${domain}: ${reason}. Until these records exist, mail from ${domain} fails SPF, DKIM and DMARC and lands in spam or bounces.`);logger.warn(` Fix: ${dnsCredentialFix(provider,envFile,ns.nameservers)}`);logger.warn(` Or add these records by hand at the DNS host:`);logger.warn(` MX @ 10 ${mailHost}`);logger.warn(` TXT @ ${spf}`);if(dkim)logger.warn(` TXT ${dkimName.padEnd(17)}${dkim}`);logger.warn(` TXT _dmarc ${dmarc}`);if(postmaster)logger.warn(` TXT @ ${postmaster}`);logger.warn(` A mail ${ip}`)};const declared=declaredDnsProvider(await loadTsCloudConfig(process.env.APP_ENV||"production").catch(()=>{return}));const providerConfigs=dnsProviderConfigsFromEnv(declared);const declaredProblem=declaredDnsProviderProblem(declared,providerConfigs);if(declaredProblem){logger.warn(` DNS: ${declaredProblem}`);return byHand(`the declared provider '${declared}' has no credentials in this environment`,declared)}if(providerConfigs.length===0)return byHand("no DNS provider credentials are configured");const provider=await resolveZoneDnsProvider(domain,providerConfigs,logger);if(!provider)return byHand(`no configured DNS provider administers this zone`);const apex=domain.toLowerCase();const dkimFqdn=`${dkimName}.${domain}`;const dmarcFqdn=`_dmarc.${domain}`;const mailFqdn=`mail.${domain}`;const recordsAt=async(fqdn,type)=>{const res=await provider.listRecords(domain);return selectRecordsAt(res?.success?res.records||[]:[],fqdn,type,domain)};const replaceTxt=async(fqdn,content,owns)=>{const existing=await recordsAt(fqdn,"TXT");const{remove,create}=planTxtReplacement(existing,content,owns);if(!create)return;for(const record of remove){const removed=await provider.deleteRecord(domain,{...record,name:fqdn,type:"TXT"});if(removed&&removed.success===false)throw new Error(`TXT ${fqdn}: could not remove the record being replaced (${removed.message||"provider refused the delete"})`)}const created=await provider.createRecord(domain,{name:fqdn,type:"TXT",content,ttl:600});if(!created?.success)throw new Error(`TXT ${fqdn}: ${created?.message||"provider rejected the record"}`)};try{const mxRecords=await recordsAt(apex,"MX");const staleMx=mxRecords.filter((r)=>String(r.content??r.value??"").replace(/\.$/,"").toLowerCase()!==mailHost.toLowerCase());for(const record of staleMx){logger.warn(` Mail DNS: replacing an existing MX for ${domain} → ${record.content??record.value}`);await provider.deleteRecord(domain,{...record,name:apex,type:"MX"})}if(mxRecords.length===staleMx.length){const created=await provider.createRecord(domain,{name:apex,type:"MX",content:mailHost,ttl:600,priority:10});if(!created?.success)throw new Error(`MX ${domain}: ${created?.message||"provider rejected the record"}`)}await replaceTxt(apex,spf,(existing)=>existing.toLowerCase().startsWith("v=spf1"));if(dkim)await replaceTxt(dkimFqdn,dkim,()=>true);await replaceTxt(dmarcFqdn,dmarc,(existing)=>existing.toLowerCase().startsWith("v=dmarc1"));if(postmaster)await replaceTxt(apex,postmaster,(existing)=>existing===postmaster);const mailA=await provider.upsertRecord(domain,{name:mailFqdn,type:"A",content:ip,ttl:600});if(!mailA?.success)throw new Error(`A ${mailFqdn}: ${mailA?.message||"provider rejected the record"}`);const verifyRes=await provider.listRecords(domain);const anomalies=verifyRes?.success?findMailDnsAnomalies(verifyRes.records||[],[{label:"MX",fqdn:apex,type:"MX"},{label:"SPF",fqdn:apex,type:"TXT",owns:(content)=>content.toLowerCase().startsWith("v=spf1")},...dkim?[{label:"DKIM",fqdn:dkimFqdn,type:"TXT"}]:[],{label:"DMARC",fqdn:dmarcFqdn,type:"TXT",owns:(content)=>content.toLowerCase().startsWith("v=dmarc1")},...postmaster?[{label:"Postmaster Tools",fqdn:apex,type:"TXT",owns:(content)=>content===postmaster}]:[]],domain):[];for(const anomaly of anomalies)logger.warn(` Mail DNS: ${anomaly}`);logger.success(`Mail DNS published for ${domain} via ${provider.name} (MX→${mailHost}, SPF, DKIM at ${dkimName}, DMARC, ${postmaster?"Postmaster Tools, ":""}${mailFqdn}→${ip})`);const hint=postmasterHint(domain,postmasterCfg);if(hint)logger.info(` ${hint}`)}catch(err){logger.warn(`Mail DNS reconcile skipped for ${domain}: ${getErrorMessage(err)}`)}}export function configDnsDomains(sites){const domains=new Set;for(const site of Object.values(sites)){if(!site?.redirect&&site?.domain&&typeof site.domain==="string")domains.add(site.domain.replace(/^www\./,""))}const all=[...domains];return all.filter((domain)=>!all.some((other)=>other!==domain&&domain.endsWith(`.${other}`)))}async function reconcileCloudflareCdnForDeploy(tsCloudConfig,ip,ipv6,logger){let resolveCloudflareCdnPlan;let reconcileCloudflareCdn;let CloudflareProvider;let normalizePublicIpv6;try{({resolveCloudflareCdnPlan,reconcileCloudflareCdn,CloudflareProvider,normalizePublicIpv6}=await import("@stacksjs/ts-cloud"))}catch{return}if(typeof resolveCloudflareCdnPlan!=="function"||typeof reconcileCloudflareCdn!=="function"){if(tsCloudConfig?.infrastructure?.compute?.proxy?.cdn?.provider==="cloudflare")logger.warn("Cloudflare CDN: installed @stacksjs/ts-cloud is too old to manage it — upgrade to ^0.9.4.");return}const{plan,errors}=resolveCloudflareCdnPlan(tsCloudConfig);for(const error of errors)logger.warn(`Cloudflare CDN: ${error}`);if(!plan)return;if(!ip){logger.warn("Cloudflare CDN: no box IP resolved — skipping.");return}logger.info(`Cloudflare CDN: reconciling ${plan.hosts.length} host(s) on ${plan.zone}...`);try{const provider=new CloudflareProvider(plan.apiToken,{zoneId:plan.zoneId,accountId:plan.accountId});const report=await reconcileCloudflareCdn({provider,zone:plan.zone,hosts:plan.hosts,ipv4:ip,ipv6:typeof normalizePublicIpv6==="function"?normalizePublicIpv6(ipv6):ipv6,proxied:plan.proxied,settings:plan.settings,cache:plan.cache,originGuard:plan.originGuard,purge:plan.purge,skipOriginProbe:plan.skipOriginProbe,edgeWait:plan.edgeWaitMs>0?{timeoutMs:plan.edgeWaitMs,whilePending:zoneDelegatedThisDeploy,onProgress:(message)=>logger.info(` ${message}`)}:undefined});for(const record of report.records)logger.success(` ${record.host} ${record.type} → ${record.content}${record.proxied?" (proxied)":" (DNS-only)"}`);for(const setting of report.settingsChanged)logger.info(` ${setting.id}: ${JSON.stringify(setting.from)} → ${JSON.stringify(setting.to)}`);if(report.cacheRules>0)logger.success(` ${report.cacheRules} cache rule(s) applied`);if(report.originGuard)logger.success(" origin guard header applied");if(report.purged)logger.success(" edge cache purged");for(const deferred of report.deferredProxy||[])logger.warn(` ${deferred.host} left DNS-only: ${deferred.reason}. The next deploy proxies it once the certificate is there.`);for(const warning of report.warnings)logger.warn(` ${warning}`)}catch(err){logger.warn(`Cloudflare CDN: ${err?.message||err}`)}}async function reconcileR2ForDeploy(tsCloudConfig,logger){const buckets=tsCloudConfig?.infrastructure?.r2?.buckets;if(!buckets||Object.keys(buckets).length===0)return;let reconcileR2Buckets;try{({reconcileR2Buckets}=await import("@stacksjs/ts-cloud"))}catch{return}if(typeof reconcileR2Buckets!=="function"){logger.warn("R2: installed @stacksjs/ts-cloud is too old to manage buckets. Upgrade it to provision infrastructure.r2.");return}const apiToken=process.env.CLOUDFLARE_API_TOKEN;const accountId=process.env.CLOUDFLARE_ACCOUNT_ID;if(!apiToken||!accountId){logger.warn("R2: CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID are both needed to provision buckets. Skipping.");return}logger.info(`R2: reconciling ${Object.keys(buckets).length} bucket(s)...`);try{const summary=await reconcileR2Buckets(tsCloudConfig,{apiToken,accountId,zoneId:process.env.CLOUDFLARE_ZONE_ID||undefined,log:(message)=>logger.info(` ${message}`)});for(const bucket of summary?.buckets??[]){const changes=bucket.changes?.length?bucket.changes.join(", "):"in sync";logger.success(` ${bucket.name}: ${changes}`);for(const domain of bucket.domains??[])logger.success(` https://${domain.domain}${domain.status?` (${domain.status})`:""}`)}for(const warning of summary?.warnings??[])logger.warn(` ${warning}`)}catch(err){logger.warn(`R2: ${err?.message||err}`)}}async function reconcileWorkersForDeploy(tsCloudConfig,logger){const workers=tsCloudConfig?.infrastructure?.workers;if(!workers||Object.keys(workers).length===0)return;let reconcileCloudflareWorkers;try{({reconcileCloudflareWorkers}=await import("@stacksjs/ts-cloud"))}catch{return}if(typeof reconcileCloudflareWorkers!=="function"){logger.warn("Workers: installed @stacksjs/ts-cloud is too old to deploy them. Upgrade it to deploy infrastructure.workers.");return}const apiToken=process.env.CLOUDFLARE_API_TOKEN;const accountId=process.env.CLOUDFLARE_ACCOUNT_ID;if(!apiToken||!accountId){logger.warn("Workers: CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID are both needed to deploy them. Skipping.");return}logger.info(`Workers: reconciling ${Object.keys(workers).length} worker(s)...`);try{const summary=await reconcileCloudflareWorkers(tsCloudConfig,{apiToken,accountId,projectRoot:process.cwd(),zoneId:process.env.CLOUDFLARE_ZONE_ID||undefined,log:(message)=>logger.info(` ${message}`)});for(const worker of summary?.workers??[]){const changes=worker.changes?.length?worker.changes.join(", "):"in sync";logger.success(` ${worker.name}: ${changes}`);for(const domain of worker.domains??[])logger.success(` https://${domain.domain}${domain.status?` (${domain.status})`:""}`)}for(const warning of summary?.warnings??[])logger.warn(` ${warning}`)}catch(err){logger.warn(`Workers: ${err?.message||err}`)}}export function dnsProviderNameFromNameservers(nameservers){const normalized=nameservers.map((name)=>name.toLowerCase().replace(/\.$/,""));if(normalized.some((name)=>name.endsWith(".porkbun.com")))return"porkbun";if(normalized.some((name)=>name.endsWith(".ns.cloudflare.com")))return"cloudflare";if(normalized.some((name)=>/(^|\.)awsdns-\d+\.(?:com|net|org|co\.uk)$/.test(name)))return"route53";if(normalized.some((name)=>name.endsWith(".domaincontrol.com")))return"godaddy";return null}async function reconcileCommsHqSendingDomain(deployEnv,tsCloudConfig,logger){const key=deployEnv.COMMSHQ_KEY;if(!key)return;try{const{setUpSendingDomainForApp}=await import("../commshq-domain-run");logger.info("CommsHQ: checking the sending domain...");const outcome=await setUpSendingDomainForApp({url:deployEnv.COMMSHQ_URL||"https://commshq.org",key,mailFrom:deployEnv.MAIL_FROM_ADDRESS,appUrl:deployEnv.APP_URL,zone:tsCloudConfig?.infrastructure?.dns?.domain,print:(line)=>logger.info(line)});if(outcome.status==="failed")logger.warn(`CommsHQ: the sending domain was not set up: ${outcome.detail}`)}catch(err){logger.warn(`CommsHQ: sending domain setup failed: ${err instanceof Error?err.message:String(err)}`)}}async function reconcileConfigDns(sites,logger){const projectDnsConfig=await loadProjectDnsConfig(dnsConfig);const declared=["a","aaaa","cname","mx","txt"].reduce((total,key)=>total+(Array.isArray(projectDnsConfig?.[key])?projectDnsConfig[key].length:0),0);if(declared===0)return;for(const domain of configDnsDomains(sites)){try{const result=await syncDnsConfig(domain,projectDnsConfig);if(!result.provider)continue;if(result.created||result.failed)logger.info(`DNS (config/dns.ts) ${domain}: ${result.created} created, ${result.kept} kept${result.failed?`, ${result.failed} failed`:""}`);for(const failure of result.failures)logger.warn(` ${failure.record.type} ${failure.record.name} → ${failure.record.content}: ${failure.reason}`);for(const skipped of result.skipped)logger.info(` skipped ${skipped.record.type} ${skipped.record.name}: ${skipped.reason}`)}catch(err){logger.warn(`DNS (config/dns.ts) reconcile for ${domain} failed: ${err instanceof Error?err.message:String(err)}`)}}}export async function syncRoutesAfterDeploy(deployEnv,logger){const key=deployEnv.STATUSHQ_KEY||process.env.STATUSHQ_KEY;if(!key)return;try{const{config}=await import("@stacksjs/config");const{collectRouteManifest,readProductionRouteContext}=await import("../hq-routes");const{runHqRouteSync}=await import("../hq");const services=config.services??{};const context=await readProductionRouteContext(deployEnv);const baseUrl=context.baseUrl;await runHqRouteSync({...services,statushq:{...services.statushq,url:deployEnv.STATUSHQ_URL||services.statushq?.url||"https://statushq.org"}},{name:String(deployEnv.APP_NAME||config.app?.name||"app")},{baseUrl,manifest:await collectRouteManifest(context.env)},{fetch:(input,init)=>fetch(input,init),print:(line)=>logger.info(line)},key)}catch(error){logger.warn(`StatusHQ: routes not synced (${error instanceof Error?error.message:String(error)}). Run \`buddy hq:sync\` to try again.`)}}let zoneDelegatedThisDeploy=false;export async function delegateDeclaredZone(config,logger){const dns=config?.tsCloud?.infrastructure?.dns??config?.infrastructure?.dns;zoneDelegatedThisDeploy=false;if(!dns?.registrar)return;try{const{applyDeclaredZoneSettings,delegateZoneFromConfig,describeDelegation,describeZoneSettings}=await import("@stacksjs/ts-cloud");const result=await delegateZoneFromConfig(dns);zoneDelegatedThisDeploy=result.status==="delegated"||result.status==="already-delegated";for(const line of describeDelegation(result))logger.info(line);if(result.status==="blocked")logger.warn("DNS: delegation did not complete; the domain still resolves through its registrar.");const settings=await applyDeclaredZoneSettings(dns);for(const line of describeZoneSettings(settings))logger.info(line);if(settings.status!=="skipped"&&settings.failed.length>0)logger.warn(`DNS: ${settings.failed.length} zone setting(s) could not be applied; the zone is serving with its previous values.`)}catch(error){logger.warn(`DNS: zone reconciliation could not run: ${error instanceof Error?error.message:String(error)}`)}}export async function reconcileHetznerDns(sites,ip,logger,ipv6,autoWww){const published=[];const{gatewayHostnames}=await import("@stacksjs/ts-cloud");const hostnames=gatewayHostnames(sites,{autoWww});const byBase=new Map;for(const fqdn of hostnames){const base=fqdn.replace(/^(?:www|\*)\./,"");const group=byBase.get(base)??new Set;group.add(fqdn);byBase.set(base,group)}if(byBase.size===0)return published;const tsCloudConfig=await loadTsCloudConfig(process.env.APP_ENV||"production").catch(()=>{return});await delegateDeclaredZone(tsCloudConfig,logger);const declared=declaredDnsProvider(tsCloudConfig);const providerConfigs=dnsProviderConfigsFromEnv(declared);const declaredProblem=declaredDnsProviderProblem(declared,providerConfigs);if(declaredProblem)logger.warn(`DNS: ${declaredProblem}`);if(providerConfigs.length===0){if(!declaredProblem)logger.warn("DNS: no DNS provider credentials found (PORKBUN_API_KEY/…); skipping DNS reconciliation.");for(const fqdn of hostnames)logger.info(` Point manually: A ${fqdn} → ${ip}`);return published}const{reconcileAddressRecords}=await import("@stacksjs/ts-cloud");logger.info("Reconciling DNS records...");const resolveA=async(fqdn)=>{try{const{resolve4}=await import("node:dns/promises");return await resolve4(fqdn)}catch{return[]}};for(const[domain,group]of byBase){const fqdns=[...group].sort();try{const provider=await resolveZoneDnsProvider(domain,providerConfigs,logger);if(!provider){for(const fqdn of fqdns){const current=await resolveA(fqdn);if(current.includes(ip))logger.success(` DNS: ${fqdn} → ${ip} (externally managed, already correct)`);else if(current.length===0)logger.warn(` DNS: ${fqdn} does not resolve and no configured provider manages ${domain} - create it manually: A ${fqdn} → ${ip}`);else logger.warn(` DNS: ${fqdn} resolves to ${current.join(", ")} but this deploy targets ${ip}, and no configured provider manages ${domain} - update it manually: A ${fqdn} → ${ip}`)}continue}for(const fqdn of fqdns){const report=await reconcileAddressRecords({provider,zone:domain,fqdn,ipv4:ip,ipv6});for(const record of report.published){logger.success(` DNS: ${record.fqdn} → ${record.content} (${provider.name})`);published.push(record.fqdn)}for(const warning of report.warnings)logger.warn(` DNS: ${warning}`)}}catch(err){logger.warn(` DNS: ${domain} reconciliation failed: ${err?.message||err}`)}}return published}async function runPreviewCommand(name,options,action){const base=resolveDeploymentEnvironment({option:options.base});if(action==="deploy")await assertPublicationAllowed({cwd:p.projectPath(),channel:"preview"});const envFile=".env.preview";if(action==="deploy"&&!existsSync(p.projectPath(envFile))){log.error(`Previews read their secrets from ${envFile} only, and this project has none.`);log.info(`Create it with its own database, mail and API credentials (never production's): buddy env:set --file ${envFile} APP_KEY ...`);process.exit(ExitCode.FatalError)}if(existsSync(p.projectPath(envFile))){const{loadEnv}=await import("@stacksjs/env");loadEnv({path:envFile,env:"preview",keysFile:".env.keys",overload:true,quiet:true})}const appConfig=await loadTsCloudConfig(base);if(!appConfig){log.error("Previews need config/cloud.ts.");process.exit(ExitCode.FatalError)}const provider=resolveProvider(appConfig);if(!isSshPipelineProvider(provider)){log.error(`Previews run as a tenant on the app's box, which the '${provider}' provider does not have. They work with cloud.provider 'hetzner' or 'ssh'.`);process.exit(ExitCode.FatalError)}let target;try{target=previewTarget(appConfig,name,previewDomain(appConfig,process.env))}catch(error){log.error(getErrorMessage(error));process.exit(ExitCode.InvalidArgument)}const sshTarget=provider==="ssh"?resolveSshTarget(appConfig):null;const lookup=provider==="ssh"?null:await resolveAttachTargetBox(target.owner,base,appConfig);const host=sshTarget?.host??lookup?.box?.publicIp;if(!host){log.error(provider==="ssh"?"No SSH host configured for this project.":describeAttachLookupFailure(target.owner,base,lookup?.failure));process.exit(ExitCode.FatalError)}const remoteTarget=sshTarget?{...sshTarget,host}:hetznerTarget(host);const{sshExecOrThrow}=await import("@stacksjs/ts-cloud");const runRemote=(script)=>{const encoded=Buffer.from(script).toString("base64");const privileged=remoteTarget.user==="root"?"bash":"sudo -n bash";return sshExecOrThrow(host,`echo ${encoded} | base64 -d | ${privileged}`,remoteExecOptions(remoteTarget,15))};if(action==="remove"){await removePreview(target,base,runRemote);return}const{buildHostSitePortsScript,occupiedHostPorts,parseHostSiteFragments}=await import("@stacksjs/ts-cloud");const owners=occupiedHostPorts(parseHostSiteFragments(await runRemote(buildHostSitePortsScript())));const port=previewPort(owners,target.slug,Number(appConfig.sites?.[target.site]?.port)||3000);log.info(`Deploying preview ${target.slug} to ${target.url} (port ${port} on ${host})`);await deployOverSsh(derivePreviewConfig(appConfig,target,port),base,{verbose:options.verbose===true,yes:true},envFile);log.success(`Preview deployed: ${target.url}`);if(process.env.GITHUB_OUTPUT)writeFileSync(process.env.GITHUB_OUTPUT,`url=${target.url}
|
|
471
489
|
`,{flag:"a"})}async function removePreview(target,base,runRemote){log.info(`Removing preview ${target.slug} (${target.host})`);await runRemote(buildPreviewTeardownScript(target.slug,target.site));log.success(`Removed ${target.slug} from the box`);const tsCloudConfig=await loadTsCloudConfig(base).catch(()=>{return});const providerConfigs=dnsProviderConfigsFromEnv(declaredDnsProvider(tsCloudConfig));const zone=target.host;const provider=providerConfigs.length>0?await resolveZoneDnsProvider(zone,providerConfigs,log):undefined;if(!provider){log.warn(`DNS: no configured provider manages ${zone}; remove the A/AAAA records for ${target.host} by hand.`)}else{const{removeAddressRecords}=await import("@stacksjs/ts-cloud");const{removed,warnings}=await removeAddressRecords(provider,zone,target.host);for(const record of removed)log.success(`DNS: deleted ${record.type} ${target.host} (${provider.name})`);for(const warning of warnings)log.warn(`DNS: ${warning}`)}const pin=join(process.cwd(),"storage","cloud","state",`${target.slug}-${base}.json`);if(existsSync(pin)){const{rmSync}=await import("node:fs");rmSync(pin)}log.success(`Preview ${target.slug} removed`)}async function deployToFlyProvider(tsCloudConfig,environment,verbose,envFile){await runBeforeDeployHook(p.projectPath(),{environment,region:tsCloudConfig.project?.region||"us-east-1"});const{FlyDeployError,runFlyDeploy}=await import("./deploy-fly");const api=await loadTsCloudDeployApi();if(typeof api.deployToFly!=="function"){log.error("This @stacksjs/ts-cloud cannot deploy to Fly.io: upgrade it to 0.16.45 or newer.");process.exit(ExitCode.FatalError)}const{execSync}=await import("node:child_process");let release;try{release=execSync("git rev-parse --short=12 HEAD",{cwd:p.projectPath(),stdio:"pipe"}).toString().trim()}catch{release=`build-${Date.now()}`}const deployEnv=environment==="prod"?"production":environment;try{const result=await runFlyDeploy({config:tsCloudConfig,environment:deployEnv,token:process.env.FLY_API_TOKEN,release,envValues:await resolveDeployEnvValues(deployEnv,tsCloudConfig,envFile),projectRoot:p.projectPath()},{api,run:(command,options)=>{const child=Bun.spawnSync(command,{cwd:options.cwd,stdin:options.stdin===undefined?"inherit":new TextEncoder().encode(options.stdin),stdout:verbose?"inherit":"pipe",stderr:verbose?"inherit":"pipe"});return{exitCode:child.exitCode,output:`${child.stdout??""}${child.stderr??""}`}},exists:existsSync,log:(line)=>log.info(line)});log.success(`Deployed to ${result.url}`);if(result.untouched.length>0)log.warn(`Left ${result.untouched.length} Machine(s) the config no longer accounts for: ${result.untouched.join(", ")}. Remove them with \`fly machine destroy\` once nothing needs their data.`);for(const certificate of result.certificates){if(certificate.configured)continue;const needs=certificate.dns_requirements;const target=needs?.cname?`a CNAME to ${needs.cname}`:[...needs?.a??[],...needs?.aaaa??[]].join(", ")||"Fly's addresses";log.info(`${certificate.hostname}: point it at ${target}; Fly issues the certificate once it resolves.`)}}catch(error){if(error instanceof FlyDeployError){log.error(error.message);if(error.hint)log.info(error.hint);process.exit(ExitCode.FatalError)}throw error}}async function buildContainerImageWithPantry(args){const{slug,sites,verbose}=args;const{execSync}=await import("node:child_process");let cli;for(const candidate of["pantry","ts-pantry"]){try{execSync(`command -v ${candidate}`,{stdio:"pipe"});cli=candidate;break}catch{}}if(!cli){log.warn("pantry CLI not found on PATH - skipping container image build. Install pantry to enable `--docker`.");return}const dockerfile="storage/framework/Dockerfile";const canPush=Boolean(process.env.PANTRY_REGISTRY_TOKEN||process.env.PANTRY_TOKEN);for(const[siteName,site]of Object.entries(sites)){if(!site?.start)continue;const tag=`${slug}-${siteName}:latest`;log.info(`[${siteName}] building image ${tag} with pantry (native, no Docker daemon)...`);const flags=["build",".","-t",tag,"-f",dockerfile,"--run-mode","skip"];if(canPush)flags.push("--push");execSync(`${cli} ${flags.map((f)=>f.includes(" ")?`'${f}'`:f).join(" ")}`,{stdio:verbose?"inherit":"pipe",maxBuffer:536870912});log.success(`[${siteName}] image built${canPush?" + pushed to the pantry registry":""}`)}}export function deploy(buddy){const descriptions={deploy:"Deploy your project",project:"Target a specific project",production:"Deploy to production",development:"Deploy to development",staging:"Deploy to staging",yes:"Confirm all prompts by default",domain:"Specify a domain to deploy to",verbose:"Enable verbose output"};buddy.command("deploy [env]",descriptions.deploy).option("--domain <domain>",descriptions.domain,{default:undefined}).option("--env-file <file>","Deploy with only this runtime environment file",{default:undefined}).option("--retire-domains <domains>","Explicitly retire omitted gateway hostnames (comma-separated)",{default:undefined}).option("-p, --project [project]",descriptions.project,{default:false}).option("--prod",descriptions.production,{default:false}).option("--dev",descriptions.development,{default:false}).option("--yes",descriptions.yes,{default:false}).option("--site <name>","Deploy only this one site to the existing server (multi-tenant surgical add)",{default:undefined}).option("--staging",descriptions.staging,{default:false}).option("--dry-run","Preview the deployment and change nothing",{default:false}).option("--hold-dns","Ship and start the release without publishing DNS, TLS, CDN or mail records (bring a new server up before a cutover)",{default:false}).option("--docker","Also build an OCI image with pantry (native, no Docker daemon) and push it to the pantry registry",{default:false}).option("-J, --json","Emit a machine-readable deployment preview",{default:false}).option("--verbose",descriptions.verbose,{default:false}).action(withDeployNotification(async(envArg,options)=>{log.debug("Running `buddy deploy` ...",options);if(process.argv.includes("--hold-dns")||options.holdDns===true)process.env.STACKS_DEPLOY_HOLD_DNS="1";const askedForDryRun=process.argv.includes("--dry-run")||options.dryRun===true;const optionEnvironment=options.env;const deployEnvName=resolveDeploymentEnvironment({positional:envArg,option:optionEnvironment,staging:options.staging,development:options.dev});const deployEnv=deployEnvName;const selectedEnvFile=explicitDeploymentEnvFile(p.projectPath(),options.envFile);if(selectedEnvFile){const values=await resolveDeployEnvValues(deployEnvName,undefined,selectedEnvFile);for(const[key,value]of Object.entries(values))process.env[key]=value}try{applyDeploymentDomainOverride({},options.domain)}catch(error){log.error(getErrorMessage(error));process.exit(ExitCode.InvalidArgument)}if(askedForDryRun){process.env.APP_ENV=deployEnvName;const envFile=selectedEnvFile??(deployEnvName==="production"?".env.production":`.env.${deployEnvName}`);if(!selectedEnvFile&&existsSync(p.projectPath(envFile))){try{const{loadEnv}=await import("@stacksjs/env");loadEnv({path:envFile,env:deployEnvName,keysFile:".env.keys",overload:true,quiet:true})}catch(error){log.debug(`Could not load ${envFile} for preview: ${getErrorMessage(error)}`)}}const tsCloudConfig=deploymentRetirements(await loadTsCloudConfig(deployEnvName)??{},options.retireDomains);validateDeploymentProviderInputs(resolveProvider(tsCloudConfig),{envFile:selectedEnvFile,retireDomains:options.retireDomains});const{resolveSiteKind}=await loadTsCloudDeployApi();const unbacked=tsCloudConfig?findUnbackedManagedServices(tsCloudConfig,await hasOffsiteBackupDestination()):[];let plan;try{plan=createDeploymentPreview({config:tsCloudConfig,environment:deployEnvName,site:options.site,domain:options.domain,docker:options.docker===true,fallbackProjectName:app.name,fallbackProjectSlug:app.name?.toLowerCase().replace(/[^a-z0-9]+/g,"-")||"app",fallbackProvider:"aws",fallbackMode:tsCloudConfig?.mode||"server",fallbackRegion:process.env.AWS_REGION||"us-east-1",resolveSiteKind,applyEnvironmentToSites,warnings:unbacked.length>0?[unbackedDataMessage(unbacked)]:[]})}catch(error){log.error(getErrorMessage(error));process.exit(ExitCode.InvalidArgument)}if(options.json||process.argv.includes("--json"))console.log(`${deploymentPreviewJsonPrefix}${JSON.stringify(plan)}`);else process.stdout.write(formatDeploymentPreview(plan));return}await assertPublicationAllowed({cwd:p.projectPath(),channel:"web"});const automatedRevision=automatedDeploymentRevision(deployEnvName);automatedRevisionCheck=await assertCurrentDeploymentRevision(automatedRevision,p.projectPath());await ensureDeployPrerequisites(options.verbose===true,deployEnvName,selectedEnvFile);process.env.APP_ENV=deployEnvName;{const envFile=selectedEnvFile??(deployEnvName==="production"?".env.production":`.env.${deployEnvName}`);if(!selectedEnvFile&&existsSync(p.projectPath(envFile))){try{const{loadEnv}=await import("@stacksjs/env");loadEnv({path:envFile,env:deployEnvName,keysFile:".env.keys",overload:true,quiet:true})}catch(err){log.warn(`Could not load ${envFile}: ${getErrorMessage(err)}`)}}}const tsCloudConfig=deploymentRetirements(await loadTsCloudConfig(deployEnvName)??{},options.retireDomains);validateDeploymentProviderInputs(resolveProvider(tsCloudConfig),{envFile:selectedEnvFile,retireDomains:options.retireDomains});if(tsCloudConfig&&resolveProvider(tsCloudConfig)==="fly"){await deployToFlyProvider(tsCloudConfig,deployEnvName,options.verbose===true,selectedEnvFile);return}if(tsCloudConfig&&isSshPipelineProvider(resolveProvider(tsCloudConfig))){await deployOverSsh(applyDeploymentDomainOverride(tsCloudConfig,options.domain),deployEnv,options,selectedEnvFile);return}if(process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY){delete process.env.AWS_PROFILE}const startTime=performance.now();console.log("");console.log("\uD83D\uDE80 Deploy");console.log("");let productionUrl;if(deployEnv==="production"||deployEnv==="prod"){const productionValues=await resolveDeployEnvValues("production",tsCloudConfig,selectedEnvFile);productionUrl=productionValues.APP_URL?.trim()||undefined;if(productionUrl)log.debug("Using APP_URL from .env.production:",productionUrl)}const envUrl=env.APP_URL;const domain=options.domain||productionUrl||envUrl||app.url;if(deployEnvName==="production"&&!options.yes)await confirmProductionDeployment();if(!domain){log.info("No domain found in your .env.production or ./config/app.ts");log.info("Please ensure your domain is properly configured.");log.info("For more info, check out the docs or join our Discord.");process.exit(ExitCode.FatalError)}log.info(`Deploying to ${italic(domain)} (${deployEnv})`);await checkIfAwsIsBootstrapped(options);options.domain=await configureDomain(domain,options,startTime);const result=await runAction(Action.Deploy,options);if(resultFailed(result)){await outro("While running the `buddy deploy`, there was an issue",{startTime,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Project deployed.",{startTime,useSeconds:true})}));buddy.command("deploy:rollback [site]","Roll back a deployment to a preserved release").option("--env <environment>","Environment to roll back",{default:"production"}).option("--to <release>","Preserved release id to activate",{default:undefined}).option("--dry-run","Preview the rollback without changing the active release",{default:false}).option("--all","Every configured site, instead of one",{default:false}).option("--only-if-live <release>","Only roll back a site whose live release is this commit (what a failed deploy switched)",{default:undefined}).option("--verbose",descriptions.verbose,{default:false}).action(async(site,options)=>{const exitCode=await runDeployRollback(site,options);if(exitCode!==ExitCode.Success)process.exit(exitCode)});buddy.command("deploy:preview <name>","Deploy a preview (e.g. pr-123) as its own tenant on the app's box, at <name>.<preview domain>").option("--base <environment>","The environment whose box the preview runs on",{default:"production"}).option("--verbose",descriptions.verbose,{default:false}).action(async(name,options)=>{await runPreviewCommand(name,options,"deploy")});buddy.command("deploy:preview:remove <name>","Remove a preview from the app's box: its services, gateway route, certificate, files and DNS records").option("--base <environment>","The environment whose box the preview runs on",{default:"production"}).option("--verbose",descriptions.verbose,{default:false}).action(async(name,options)=>{await runPreviewCommand(name,options,"remove")});onUnknownSubcommand(buddy,"deploy")}async function confirmProductionDeployment(){if(!process.stdin.isTTY){log.error("Refusing to deploy to production from a non-interactive shell without confirmation.");log.info(" ➡️ Re-run with `--yes` to confirm (e.g. in CI): `buddy deploy --prod --yes`");process.exit(ExitCode.InvalidArgument)}const confirmed=await prompts.confirm({message:"Are you sure you want to deploy to production?",initial:true});if(!confirmed){log.info("Aborting deployment...");process.exit(ExitCode.InvalidArgument)}}async function configureDomain(domain,options,startTime){log.debug("Configuring domain...",domain);if(!domain){log.info("We could not identify a domain to deploy to.");log.warn("Please set your .env or ./config/app.ts properly.");log.info("Alternatively, specify a domain to deploy via the `--domain` flag.");console.log("");log.info(" ➡️ Example: `buddy deploy --domain example.com`");console.log("");process.exit(ExitCode.FatalError)}if(domain.includes("localhost")){log.info("You are deploying to a local environment.");log.warn("Please set your .env or ./config/app.ts properly. The domain we are deploying cannot be a `localhost` domain.");log.info("Alternatively, specify a domain to deploy via the `--domain` flag.");console.log("");log.info(" ➡️ Example: `buddy deploy --domain example.com`");console.log("");process.exit(ExitCode.FatalError)}if(await hasUserDomainBeenAddedToCloud(domain)){log.info("Domain is properly configured");log.info("Your cloud is deploying...");log.info(`${italic("This may take a while...")}`);return domain}console.log("");log.info(` \uD83D\uDC4B It appears to be your first ${italic(domain)} deployment.`);console.log("");log.info(italic("Let’s ensure it is all connected properly."));log.info(italic("One moment..."));console.log("");const result=await addDomain({...options,deploy:true,startTime});if(resultFailed(result)){await outro("While running the `buddy deploy`, there was an issue",{startTime,useSeconds:true},result.error);process.exit(ExitCode.FatalError)}await outro("Added your domain.",{startTime,useSeconds:true});process.exit(ExitCode.Success)}async function promptAndSaveCredentials(){const accessKeyId=await prompts.text({message:"AWS Access Key ID:",validate:(value)=>value.length>0?true:"Access Key ID is required"});if(!accessKeyId){log.info("Deployment cancelled");process.exit(ExitCode.Success)}const secretAccessKey=await prompts.password({message:"AWS Secret Access Key:",validate:(value)=>value.length>0?true:"Secret Access Key is required"});if(!secretAccessKey){log.info("Deployment cancelled");process.exit(ExitCode.Success)}const region=await prompts.text({message:"AWS Region:",initial:"us-east-1"});if(!region){log.info("Deployment cancelled");process.exit(ExitCode.Success)}const{setEnv}=await import("@stacksjs/env");await setEnv("AWS_ACCESS_KEY_ID",accessKeyId,{file:".env.production"});await setEnv("AWS_SECRET_ACCESS_KEY",secretAccessKey,{file:".env.production"});await setEnv("AWS_REGION",region||"us-east-1",{file:".env.production"});process.env.AWS_ACCESS_KEY_ID=accessKeyId;process.env.AWS_SECRET_ACCESS_KEY=secretAccessKey;process.env.AWS_REGION=region||"us-east-1";log.success("AWS credentials saved securely to .env.production");console.log("")}function loadAwsCredentialsFromEnv(){const environment=process.env.APP_ENV||process.env.NODE_ENV||"production";const envFiles=[p.projectPath(`.env.${environment}`),p.projectPath(".env")];for(const envPath of envFiles){if(!existsSync(envPath)){continue}try{const content=readFileSync(envPath,"utf-8");const lines=content.split(`
|
|
472
490
|
`);let accessKeyId;let secretAccessKey;let region;let accountId;for(const line of lines){const trimmed=line.trim();if(trimmed.startsWith("#")||!trimmed.includes("=")){continue}const[key,...valueParts]=trimmed.split("=");const value=valueParts.join("=").trim();if(key==="AWS_ACCESS_KEY_ID"&&value){accessKeyId=value}else if(key==="AWS_SECRET_ACCESS_KEY"&&value){secretAccessKey=value}else if(key==="AWS_REGION"&&value){region=value}else if(key==="AWS_ACCOUNT_ID"&&value){accountId=value}}if(accessKeyId&&secretAccessKey){log.debug(`Found AWS credentials in ${envPath}`);return{accessKeyId,secretAccessKey,region,accountId}}}catch(error){log.debug(`Failed to read ${envPath} file:`,error)}}return{}}async function checkIfAwsIsBootstrapped(options){let handlingAlreadyExists=false;try{log.info("Ensuring AWS cloud stack exists...");let hasCredentials=process.env.AWS_ACCESS_KEY_ID&&process.env.AWS_SECRET_ACCESS_KEY;if(!hasCredentials){const envCredentials=loadAwsCredentialsFromEnv();if(envCredentials.accessKeyId&&envCredentials.secretAccessKey){process.env.AWS_ACCESS_KEY_ID=envCredentials.accessKeyId;process.env.AWS_SECRET_ACCESS_KEY=envCredentials.secretAccessKey;if(envCredentials.region&&!process.env.AWS_REGION){process.env.AWS_REGION=envCredentials.region}if(envCredentials.accountId&&!process.env.AWS_ACCOUNT_ID){process.env.AWS_ACCOUNT_ID=envCredentials.accountId}hasCredentials=true;const environment=process.env.APP_ENV||process.env.NODE_ENV||"production";log.success(`Using AWS credentials from .env.${environment}`)}}if(!hasCredentials){const fileCredentials=loadAwsCredentialsFromFile();if(fileCredentials.accessKeyId&&fileCredentials.secretAccessKey){process.env.AWS_ACCESS_KEY_ID=fileCredentials.accessKeyId;process.env.AWS_SECRET_ACCESS_KEY=fileCredentials.secretAccessKey;if(fileCredentials.region&&!process.env.AWS_REGION){process.env.AWS_REGION=fileCredentials.region}hasCredentials=true;log.success("Using AWS credentials from ~/.aws/credentials")}}if(!hasCredentials){log.info("AWS credentials not found in .env or ~/.aws/credentials.");log.info("You can either:");log.info(" 1. Set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in .env.production");log.info(" 2. Add credentials to ~/.aws/credentials");log.info(" 3. Configure them interactively below");console.log("");if(options?.yes){log.info("Skipping credential setup (--yes flag provided)");process.exit(ExitCode.FatalError)}const setupCredentials=await prompts.confirm({message:"Would you like to configure AWS credentials now?",initial:true});log.debug("setupCredentials response:",setupCredentials,typeof setupCredentials);if(setupCredentials===undefined||setupCredentials===false){if(setupCredentials===undefined){console.log("");log.info("Deployment cancelled");process.exit(ExitCode.Success)}console.log("");log.info("Skipping cloud infrastructure check");log.info("You can configure AWS credentials later by running: buddy configure:aws");return true}await promptAndSaveCredentials()}else{log.success("AWS credentials found")}const appName=(process.env.APP_NAME||app.name||"stacks").toLowerCase().replace(/[^a-z0-9-]/g,"-");const{stacksCloudName,stacksCloudRegion}=await import("@stacksjs/cloud");const stackName=await stacksCloudName();const{AWSCloudFormationClient}=await import("@stacksjs/ts-cloud");const cfnClient=new AWSCloudFormationClient(await stacksCloudRegion());let stackExists=false;let needsEmailUpdate=false;try{const stack=(await cfnClient.describeStacks({stackName})).Stacks?.[0];if(stack){stackExists=true;log.success("Cloud stack exists");const{AWSCloudFormationClient}=await import("@stacksjs/ts-cloud");const awsCfnClient=new AWSCloudFormationClient(process.env.AWS_REGION||"us-east-1");const resources=await awsCfnClient.listStackResources(stackName);const hasEmailBucket=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="EmailBucket");const hasOutboundLambda=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="OutboundEmailLambda");const hasConversionLambda=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="EmailConversionLambda");const hasNotificationTopic=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="EmailNotificationTopic");const hasMailApiLambda=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="MailApiLambda");const hasMailUsersTable=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="MailUsersTable");const hasMailServerInstance=resources.StackResourceSummaries?.some((r)=>r.LogicalResourceId==="MailServerInstance");const currentEmailDomain=stack.Outputs?.find((o)=>o.OutputKey==="EmailDomain")?.OutputValue;const configuredDomain=(emailConfig?.from?.address?.includes("@")?emailConfig.from.address.split("@")[1]:undefined)||"stacksjs.com";if(!hasEmailBucket&&emailConfig?.server?.scan!==undefined){log.info("Email infrastructure not found in stack, will update...");needsEmailUpdate=true}else if(currentEmailDomain&¤tEmailDomain!==configuredDomain){log.info(`Email domain changed: ${currentEmailDomain} -> ${configuredDomain}, will update...`);needsEmailUpdate=true}else if(hasEmailBucket&&(!hasOutboundLambda||!hasConversionLambda||!hasNotificationTopic)){log.info("Email infrastructure incomplete, will update...");needsEmailUpdate=true}else if(hasEmailBucket&&(!hasMailApiLambda||!hasMailUsersTable)){log.info("Mail API infrastructure missing, will update...");needsEmailUpdate=true}else if(hasEmailBucket&&!hasMailServerInstance&&emailConfig?.server?.enabled){log.info("Mail server EC2 instance missing, will update...");needsEmailUpdate=true}const currentMode=(stack.Outputs||[]).find((o)=>o.OutputKey==="MailServerMode")?.OutputValue;const configuredMode=emailConfig?.server?.mode||"serverless";if(currentMode&¤tMode!==configuredMode){log.info(`Mail server mode changed: ${currentMode} -> ${configuredMode}, will update...`);needsEmailUpdate=true}if(hasMailServerInstance&&emailConfig?.server?.enabled){const forceMailUpdate=process.env.FORCE_MAIL_UPDATE==="true";if(forceMailUpdate){log.info("Forcing mail server update...");needsEmailUpdate=true}}if(!needsEmailUpdate){return true}}}catch(error){const caught=error&&typeof error==="object"?error:{message:String(error)};log.debug(`Stack not found: ${getErrorMessage(error)}`)}if(!stackExists){log.info("Cloud stack not found, will be created by deploy action")}return true;log.info("Creating/updating cloud infrastructure. This may take a few moments...");const emailDomain=emailConfig?.from?.address?.split("@")?.[1]||"stacksjs.com";const emailBucketName=`${appName}-emails`;const region=process.env.AWS_REGION||"us-east-1";const enableEmailServer=emailConfig?.server?.scan!==undefined;log.info(`Email domain: ${emailDomain}`);log.info(`Email server enabled: ${enableEmailServer}`);const cloud=await loadTsCloudConfig(process.env.APP_ENV||"production");const hostedZoneId=cloud?.tsCloud?.infrastructure?.dns?.hostedZoneId||cloud?.infrastructure?.dns?.hostedZoneId||process.env.AWS_HOSTED_ZONE_ID;if(!hostedZoneId){log.error("No Route 53 hosted zone found. Set `infrastructure.dns.hostedZoneId` in config/cloud.ts, or AWS_HOSTED_ZONE_ID in this environment.");return false}const template={AWSTemplateFormatVersion:"2010-09-09",Description:`${appName} Cloud Infrastructure with Email Server`,Resources:{StacksBucket:{Type:"AWS::S3::Bucket",Properties:{BucketName:`${appName}-${process.env.APP_ENV||"production"}-assets`,PublicAccessBlockConfiguration:{BlockPublicAcls:false,BlockPublicPolicy:false,IgnorePublicAcls:false,RestrictPublicBuckets:false},WebsiteConfiguration:{IndexDocument:"index.html",ErrorDocument:"error.html"}}}},Outputs:{BucketName:{Description:"Name of the S3 bucket",Value:{Ref:"StacksBucket"},Export:{Name:`${appName}BucketName`}},BucketWebsiteURL:{Description:"URL of the S3 bucket website",Value:{"Fn::GetAtt":["StacksBucket","WebsiteURL"]}}}};if(enableEmailServer){log.info("Adding email server infrastructure...");template.Resources.EmailBucket={Type:"AWS::S3::Bucket",Properties:{BucketName:emailBucketName,LifecycleConfiguration:{Rules:[{Id:"ArchiveOldEmails",Status:"Enabled",Transitions:[{StorageClass:"GLACIER",TransitionInDays:90}]}]},Tags:[{Key:"Purpose",Value:"EmailStorage"},{Key:"ManagedBy",Value:"Stacks"}]}};template.Resources.EmailBucketPolicy={Type:"AWS::S3::BucketPolicy",Properties:{Bucket:{Ref:"EmailBucket"},PolicyDocument:{Version:"2012-10-17",Statement:[{Sid:"AllowSESPuts",Effect:"Allow",Principal:{Service:"ses.amazonaws.com"},Action:"s3:PutObject",Resource:{"Fn::Sub":"arn:aws:s3:::${EmailBucket}/*"},Condition:{StringEquals:{"AWS:SourceAccount":{Ref:"AWS::AccountId"}}}}]}}};template.Resources.EmailIdentity={Type:"AWS::SES::EmailIdentity",Properties:{EmailIdentity:emailDomain,DkimSigningAttributes:{NextSigningKeyLength:"RSA_2048_BIT"},FeedbackAttributes:{EmailForwardingEnabled:true}}};template.Resources.EmailConfigurationSet={Type:"AWS::SES::ConfigurationSet",Properties:{Name:`${appName}-email-config`,ReputationOptions:{ReputationMetricsEnabled:true},SendingOptions:{SendingEnabled:true},SuppressionOptions:{SuppressedReasons:["BOUNCE","COMPLAINT"]}}};template.Resources.EmailLambdaRole={Type:"AWS::IAM::Role",Properties:{RoleName:`${appName}-email-lambda-role`,AssumeRolePolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Principal:{Service:"lambda.amazonaws.com"},Action:"sts:AssumeRole"}]},ManagedPolicyArns:["arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"],Policies:[{PolicyName:"EmailLambdaPolicy",PolicyDocument:{Version:"2012-10-17",Statement:[{Effect:"Allow",Action:["s3:GetObject","s3:PutObject","s3:DeleteObject","s3:ListBucket"],Resource:[{"Fn::GetAtt":["EmailBucket","Arn"]},{"Fn::Sub":"${EmailBucket.Arn}/*"}]},{Effect:"Allow",Action:["ses:SendEmail","ses:SendRawEmail"],Resource:"*"},{Effect:"Allow",Action:["dynamodb:GetItem","dynamodb:PutItem","dynamodb:UpdateItem","dynamodb:DeleteItem","dynamodb:Query","dynamodb:Scan"],Resource:{"Fn::Sub":`arn:aws:dynamodb:\${AWS::Region}:\${AWS::AccountId}:table/${appName}-mail-users`}}]}}],Tags:[{Key:"Purpose",Value:"EmailProcessing"},{Key:"ManagedBy",Value:"Stacks"}]}};template.Resources.InboundEmailLambda={Type:"AWS::Lambda::Function",DependsOn:["EmailLambdaRole"],Properties:{FunctionName:`${appName}-inbound-email`,Runtime:"nodejs20.x",Handler:"index.handler",Role:{"Fn::GetAtt":["EmailLambdaRole","Arn"]},Timeout:60,MemorySize:512,Environment:{Variables:{S3_BUCKET:emailBucketName,ORGANIZED_PREFIX:"organized/"}},Code:{ZipFile:`
|
|
473
491
|
const { S3Client, GetObjectCommand, PutObjectCommand } = require('@aws-sdk/client-s3');
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/buddy",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.617",
|
|
6
6
|
"description": "Meet Buddy. The Stacks runtime.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -95,71 +95,71 @@
|
|
|
95
95
|
"prepublishOnly": "bun run build"
|
|
96
96
|
},
|
|
97
97
|
"dependencies": {
|
|
98
|
-
"@stacksjs/actions": "0.75.
|
|
99
|
-
"@stacksjs/docs": "0.75.
|
|
100
|
-
"@stacksjs/ai": "0.75.
|
|
101
|
-
"@stacksjs/alias": "0.75.
|
|
102
|
-
"@stacksjs/analytics": "0.75.
|
|
103
|
-
"@stacksjs/api": "0.75.
|
|
104
|
-
"@stacksjs/arrays": "0.75.
|
|
105
|
-
"@stacksjs/auth": "0.75.
|
|
106
|
-
"@stacksjs/browser-extension": "0.75.
|
|
107
|
-
"@stacksjs/build": "0.75.
|
|
98
|
+
"@stacksjs/actions": "0.75.617",
|
|
99
|
+
"@stacksjs/docs": "0.75.617",
|
|
100
|
+
"@stacksjs/ai": "0.75.617",
|
|
101
|
+
"@stacksjs/alias": "0.75.617",
|
|
102
|
+
"@stacksjs/analytics": "0.75.617",
|
|
103
|
+
"@stacksjs/api": "0.75.617",
|
|
104
|
+
"@stacksjs/arrays": "0.75.617",
|
|
105
|
+
"@stacksjs/auth": "0.75.617",
|
|
106
|
+
"@stacksjs/browser-extension": "0.75.617",
|
|
107
|
+
"@stacksjs/build": "0.75.617",
|
|
108
108
|
"@stacksjs/bumpx": "^0.2.32",
|
|
109
|
-
"@stacksjs/cache": "0.75.
|
|
110
|
-
"@stacksjs/chat": "0.75.
|
|
109
|
+
"@stacksjs/cache": "0.75.617",
|
|
110
|
+
"@stacksjs/chat": "0.75.617",
|
|
111
111
|
"@stacksjs/clapp": "^0.2.17",
|
|
112
|
-
"@stacksjs/cli": "0.75.
|
|
113
|
-
"@stacksjs/cloud": "0.75.
|
|
114
|
-
"@stacksjs/cms": "0.75.
|
|
115
|
-
"@stacksjs/collections": "0.75.
|
|
116
|
-
"@stacksjs/commerce": "0.75.
|
|
117
|
-
"@stacksjs/config": "0.75.
|
|
118
|
-
"@stacksjs/database": "0.75.
|
|
119
|
-
"@stacksjs/desktop-build": "0.75.
|
|
120
|
-
"@stacksjs/dns": "0.75.
|
|
112
|
+
"@stacksjs/cli": "0.75.617",
|
|
113
|
+
"@stacksjs/cloud": "0.75.617",
|
|
114
|
+
"@stacksjs/cms": "0.75.617",
|
|
115
|
+
"@stacksjs/collections": "0.75.617",
|
|
116
|
+
"@stacksjs/commerce": "0.75.617",
|
|
117
|
+
"@stacksjs/config": "0.75.617",
|
|
118
|
+
"@stacksjs/database": "0.75.617",
|
|
119
|
+
"@stacksjs/desktop-build": "0.75.617",
|
|
120
|
+
"@stacksjs/dns": "0.75.617",
|
|
121
121
|
"@stacksjs/dnsx": "^0.2.3",
|
|
122
|
-
"@stacksjs/email": "0.75.
|
|
123
|
-
"@stacksjs/enums": "0.75.
|
|
124
|
-
"@stacksjs/env": "0.75.
|
|
125
|
-
"@stacksjs/error-handling": "0.75.
|
|
126
|
-
"@stacksjs/events": "0.75.
|
|
127
|
-
"@stacksjs/features": "0.75.
|
|
128
|
-
"@stacksjs/git": "0.75.
|
|
122
|
+
"@stacksjs/email": "0.75.617",
|
|
123
|
+
"@stacksjs/enums": "0.75.617",
|
|
124
|
+
"@stacksjs/env": "0.75.617",
|
|
125
|
+
"@stacksjs/error-handling": "0.75.617",
|
|
126
|
+
"@stacksjs/events": "0.75.617",
|
|
127
|
+
"@stacksjs/features": "0.75.617",
|
|
128
|
+
"@stacksjs/git": "0.75.617",
|
|
129
129
|
"@stacksjs/gitit": "^0.2.5",
|
|
130
|
-
"@stacksjs/health": "0.75.
|
|
131
|
-
"@stacksjs/hq": "0.75.
|
|
130
|
+
"@stacksjs/health": "0.75.617",
|
|
131
|
+
"@stacksjs/hq": "0.75.617",
|
|
132
132
|
"@stacksjs/httx": "^0.1.10",
|
|
133
|
-
"@stacksjs/image": "0.75.
|
|
134
|
-
"@stacksjs/lint": "0.75.
|
|
135
|
-
"@stacksjs/logging": "0.75.
|
|
136
|
-
"@stacksjs/notifications": "0.75.
|
|
137
|
-
"@stacksjs/objects": "0.75.
|
|
138
|
-
"@stacksjs/orm": "0.75.
|
|
139
|
-
"@stacksjs/path": "0.75.
|
|
140
|
-
"@stacksjs/payments": "0.75.
|
|
141
|
-
"@stacksjs/realtime": "0.75.
|
|
142
|
-
"@stacksjs/router": "0.75.
|
|
133
|
+
"@stacksjs/image": "0.75.617",
|
|
134
|
+
"@stacksjs/lint": "0.75.617",
|
|
135
|
+
"@stacksjs/logging": "0.75.617",
|
|
136
|
+
"@stacksjs/notifications": "0.75.617",
|
|
137
|
+
"@stacksjs/objects": "0.75.617",
|
|
138
|
+
"@stacksjs/orm": "0.75.617",
|
|
139
|
+
"@stacksjs/path": "0.75.617",
|
|
140
|
+
"@stacksjs/payments": "0.75.617",
|
|
141
|
+
"@stacksjs/realtime": "0.75.617",
|
|
142
|
+
"@stacksjs/router": "0.75.617",
|
|
143
143
|
"@stacksjs/rpx": "^0.11.54",
|
|
144
|
-
"@stacksjs/scheduler": "0.75.
|
|
145
|
-
"@stacksjs/search-engine": "0.75.
|
|
146
|
-
"@stacksjs/security": "0.75.
|
|
147
|
-
"@stacksjs/server": "0.75.
|
|
148
|
-
"@stacksjs/sites": "0.75.
|
|
149
|
-
"@stacksjs/skills": "0.75.
|
|
150
|
-
"@stacksjs/socials": "0.75.
|
|
151
|
-
"@stacksjs/storage": "0.75.
|
|
152
|
-
"@stacksjs/strings": "0.75.
|
|
144
|
+
"@stacksjs/scheduler": "0.75.617",
|
|
145
|
+
"@stacksjs/search-engine": "0.75.617",
|
|
146
|
+
"@stacksjs/security": "0.75.617",
|
|
147
|
+
"@stacksjs/server": "0.75.617",
|
|
148
|
+
"@stacksjs/sites": "0.75.617",
|
|
149
|
+
"@stacksjs/skills": "0.75.617",
|
|
150
|
+
"@stacksjs/socials": "0.75.617",
|
|
151
|
+
"@stacksjs/storage": "0.75.617",
|
|
152
|
+
"@stacksjs/strings": "0.75.617",
|
|
153
153
|
"@stacksjs/stx": "^0.2.889",
|
|
154
|
-
"@stacksjs/testing": "0.75.
|
|
155
|
-
"@stacksjs/tinker": "0.75.
|
|
154
|
+
"@stacksjs/testing": "0.75.617",
|
|
155
|
+
"@stacksjs/tinker": "0.75.617",
|
|
156
156
|
"@stacksjs/tlsx": "^0.13.19",
|
|
157
157
|
"@stacksjs/ts-cloud": "^0.16.137",
|
|
158
|
-
"@stacksjs/tunnel": "0.75.
|
|
159
|
-
"@stacksjs/types": "0.75.
|
|
160
|
-
"@stacksjs/ui": "0.75.
|
|
161
|
-
"@stacksjs/utils": "0.75.
|
|
162
|
-
"@stacksjs/validation": "0.75.
|
|
158
|
+
"@stacksjs/tunnel": "0.75.617",
|
|
159
|
+
"@stacksjs/types": "0.75.617",
|
|
160
|
+
"@stacksjs/ui": "0.75.617",
|
|
161
|
+
"@stacksjs/utils": "0.75.617",
|
|
162
|
+
"@stacksjs/validation": "0.75.617",
|
|
163
163
|
"ajv": "^8.20.0",
|
|
164
164
|
"ajv-formats": "^3.0.1",
|
|
165
165
|
"bun-plugin-stx": "^0.2.889",
|