@stacksjs/buddy 0.75.602 → 0.75.606

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.
@@ -9,7 +9,7 @@ cloud-init may have failed: SSH in and check /var/log/cloud-init-output.log. Rai
9
9
  unit=$(systemctl status "$pid" 2>/dev/null | head -1 | grep -oE '[a-zA-Z0-9_.@-]+\\.service' | head -1)
10
10
  echo "$p \${unit:-unknown}"
11
11
  done`,encoding:"utf8",stdio:["pipe","pipe","pipe"]})}catch{return}const clashes=[];for(const line of listing.split(`
12
- `)){const[portText,unit="unknown"]=line.trim().split(/\s+/);const port=Number(portText);if(!Number.isFinite(port)||!wanted.has(port))continue;if(unit.startsWith(`${slug}-`))continue;clashes.push(` ${port} (site '${wanted.get(port)}') is held by ${unit}`)}if(clashes.length===0)return;log.error("Another service on the box is already listening on a port this project wants:");for(const clash of clashes)log.error(clash);log.error("Two services on one port do not error: the kernel load-balances, and each domain serves the other's site about half the time.");log.info("Pick free ports in config/cloud.ts. `ss -lntp` on the box lists what is taken.");process.exit(ExitCode.FatalError)}export async function resolveDeployEnvValues(environment,tsCloudConfig,fileOverride){const fileName=fileOverride??(environment==="production"?".env.production":environment==="staging"?".env.staging":existsSync(p.projectPath(".env.development"))?".env.development":".env");const filePath=p.projectPath(fileName);if(!existsSync(filePath))return{};try{const{getEnv}=await import("@stacksjs/env");const result=getEnv(undefined,{file:fileName,format:"json"});if(!result.success||!result.output)throw new Error("The environment could not be read completely");const parsed=JSON.parse(result.output);const values={};const undecrypted=[];for(const[key,value]of Object.entries(parsed)){if(/^DOTENV_(PUBLIC|PRIVATE)_KEY/.test(key))continue;values[key]=String(value);if(/^(?:encrypted|enc):/.test(values[key]))undecrypted.push(key)}if(undecrypted.length>0)throw new Error("The environment still contains ciphertext");const{foreignTenantKeys,partitionTenantEnv}=await import("@stacksjs/env");const partition=partitionTenantEnv(values,{self:tsCloudConfig?.project?.slug,tenants:await resolveDeclaredTenants()});for(const{tenant,keys}of foreignTenantKeys(partition)){log.warn(`[deploy] Skipping ${keys.length} '${tenant}' key(s) in ${fileName} - they belong to that tenant's own repository, and shipping them writes its secrets into this project's site .env files. Remove them with: buddy env:check --file ${fileName}. Keys: ${keys.join(", ")}`)}return partition.own}catch{throw new Error(`Cannot load deployment environment from ${fileName}; restore its decryption key and readable file before deploying.${deployEnvFailureDetail(filePath,fileName)}`)}}export function deployEnvFailureDetail(filePath,fileName){let text;try{text=readFileSync(filePath,"utf8")}catch{return""}const encrypted=[];let publicKeyName="";for(const line of text.split(/\r?\n/)){const match=line.match(/^\s*(?:export\s+)?([A-Z0-9_]+)\s*=\s*['"]?(.*)$/i);if(!match)continue;const key=match[1]??"";const value=match[2]??"";if(/^DOTENV_PUBLIC_KEY/.test(key)){publicKeyName=key;continue}if(/^(?:encrypted|enc):/.test(value))encrypted.push(key)}if(encrypted.length===0)return"";const privateKeyName=publicKeyName?publicKeyName.replace("DOTENV_PUBLIC_KEY","DOTENV_PRIVATE_KEY"):"DOTENV_PRIVATE_KEY";const keysFile=join(dirname(filePath),".env.keys");const source=process.env[privateKeyName]?`${privateKeyName} is set but does not decrypt them; it must be the private half of ${publicKeyName||"the public key in the file"}`:existsSync(keysFile)?`${privateKeyName} is not set in the environment, and .env.keys did not supply a matching one`:`${privateKeyName} is not set in the environment and there is no .env.keys beside ${fileName}`;return` Encrypted in ${fileName}: ${encrypted.join(", ")}. ${source}.`}export function mergeSiteDeployEnv(sites,resolvedDeployEnv){return Object.fromEntries(Object.entries(sites).map(([siteName,site])=>{if(!site)return[siteName,site];const base=site.inheritEnv===false?{}:{...resolvedDeployEnv};if(site.port!==undefined)delete base.PORT;return[siteName,{...site,env:{...base,...site.env||{}}}]}))}function looksLikeSqliteFile(value){return typeof value==="string"&&/\.(?:sqlite3?|db)$/i.test(value.trim())}export function siteSqlitePath(siteEnv={}){const connection=String(siteEnv.DB_CONNECTION??"sqlite").trim().toLowerCase();if(connection!=="sqlite")return null;const configured=typeof siteEnv.DB_DATABASE_PATH==="string"&&siteEnv.DB_DATABASE_PATH.trim()?siteEnv.DB_DATABASE_PATH:looksLikeSqliteFile(siteEnv.DB_DATABASE)?siteEnv.DB_DATABASE:"database/stacks.sqlite";const path=String(configured).trim().replace(/^\.\//,"");if(!path||path.startsWith("/")||path.startsWith("~")||path.split("/").includes(".."))return null;return path}export function tsCloudPersistentStateSupport(buildSiteDeployScript){const missing=[];if(typeof buildSiteDeployScript!=="function")return{ok:false,missing:["buildSiteDeployScript"]};const target="/var/www/probe-shared/database/probe.sqlite";let script="";try{script=buildSiteDeployScript({siteName:"probe",slug:"probe",appDir:"/var/www/probe-probe",artifactFetch:[],releaseId:"probe",execStart:"/bin/true",envEntries:{},port:3000,sharedPaths:[{path:"database/probe.sqlite",target,seed:true}]}).join(`
12
+ `)){const[portText,unit="unknown"]=line.trim().split(/\s+/);const port=Number(portText);if(!Number.isFinite(port)||!wanted.has(port))continue;if(unit.startsWith(`${slug}-`))continue;clashes.push(` ${port} (site '${wanted.get(port)}') is held by ${unit}`)}if(clashes.length===0)return;log.error("Another service on the box is already listening on a port this project wants:");for(const clash of clashes)log.error(clash);log.error("Two services on one port do not error: the kernel load-balances, and each domain serves the other's site about half the time.");log.info("Pick free ports in config/cloud.ts. `ss -lntp` on the box lists what is taken.");process.exit(ExitCode.FatalError)}export async function resolveDeployEnvValues(environment,tsCloudConfig,fileOverride){const fileName=fileOverride??(environment==="production"?".env.production":environment==="staging"?".env.staging":existsSync(p.projectPath(".env.development"))?".env.development":".env");const filePath=p.projectPath(fileName);if(!existsSync(filePath))return{};try{const{getEnv}=await import("@stacksjs/env");const result=getEnv(undefined,{file:fileName,format:"json"});if(!result.success||!result.output)throw new Error("The environment could not be read completely");const parsed=JSON.parse(result.output);const values={};const undecrypted=[];for(const[key,value]of Object.entries(parsed)){if(/^DOTENV_(PUBLIC|PRIVATE)_KEY/.test(key))continue;values[key]=String(value);if(/^(?:encrypted|enc):/.test(values[key]))undecrypted.push(key)}if(undecrypted.length>0)throw new Error("The environment still contains ciphertext");const{foreignTenantKeys,partitionTenantEnv}=await import("@stacksjs/env");const{HQ_CONNECTION_ENV_KEYS}=await import("../hq");const partition=partitionTenantEnv(values,{self:tsCloudConfig?.project?.slug,tenants:await resolveDeclaredTenants(),shared:HQ_CONNECTION_ENV_KEYS});for(const{tenant,keys}of foreignTenantKeys(partition)){log.warn(`[deploy] Skipping ${keys.length} '${tenant}' key(s) in ${fileName} - they belong to that tenant's own repository, and shipping them writes its secrets into this project's site .env files. Remove them with: buddy env:check --file ${fileName}. Keys: ${keys.join(", ")}`)}return partition.own}catch{throw new Error(`Cannot load deployment environment from ${fileName}; restore its decryption key and readable file before deploying.${deployEnvFailureDetail(filePath,fileName)}`)}}export function deployEnvFailureDetail(filePath,fileName){let text;try{text=readFileSync(filePath,"utf8")}catch{return""}const encrypted=[];let publicKeyName="";for(const line of text.split(/\r?\n/)){const match=line.match(/^\s*(?:export\s+)?([A-Z0-9_]+)\s*=\s*['"]?(.*)$/i);if(!match)continue;const key=match[1]??"";const value=match[2]??"";if(/^DOTENV_PUBLIC_KEY/.test(key)){publicKeyName=key;continue}if(/^(?:encrypted|enc):/.test(value))encrypted.push(key)}if(encrypted.length===0)return"";const privateKeyName=publicKeyName?publicKeyName.replace("DOTENV_PUBLIC_KEY","DOTENV_PRIVATE_KEY"):"DOTENV_PRIVATE_KEY";const keysFile=join(dirname(filePath),".env.keys");const source=process.env[privateKeyName]?`${privateKeyName} is set but does not decrypt them; it must be the private half of ${publicKeyName||"the public key in the file"}`:existsSync(keysFile)?`${privateKeyName} is not set in the environment, and .env.keys did not supply a matching one`:`${privateKeyName} is not set in the environment and there is no .env.keys beside ${fileName}`;return` Encrypted in ${fileName}: ${encrypted.join(", ")}. ${source}.`}export function mergeSiteDeployEnv(sites,resolvedDeployEnv){return Object.fromEntries(Object.entries(sites).map(([siteName,site])=>{if(!site)return[siteName,site];const base=site.inheritEnv===false?{}:{...resolvedDeployEnv};if(site.port!==undefined)delete base.PORT;return[siteName,{...site,env:{...base,...site.env||{}}}]}))}function looksLikeSqliteFile(value){return typeof value==="string"&&/\.(?:sqlite3?|db)$/i.test(value.trim())}export function siteSqlitePath(siteEnv={}){const connection=String(siteEnv.DB_CONNECTION??"sqlite").trim().toLowerCase();if(connection!=="sqlite")return null;const configured=typeof siteEnv.DB_DATABASE_PATH==="string"&&siteEnv.DB_DATABASE_PATH.trim()?siteEnv.DB_DATABASE_PATH:looksLikeSqliteFile(siteEnv.DB_DATABASE)?siteEnv.DB_DATABASE:"database/stacks.sqlite";const path=String(configured).trim().replace(/^\.\//,"");if(!path||path.startsWith("/")||path.startsWith("~")||path.split("/").includes(".."))return null;return path}export function tsCloudPersistentStateSupport(buildSiteDeployScript){const missing=[];if(typeof buildSiteDeployScript!=="function")return{ok:false,missing:["buildSiteDeployScript"]};const target="/var/www/probe-shared/database/probe.sqlite";let script="";try{script=buildSiteDeployScript({siteName:"probe",slug:"probe",appDir:"/var/www/probe-probe",artifactFetch:[],releaseId:"probe",execStart:"/bin/true",envEntries:{},port:3000,sharedPaths:[{path:"database/probe.sqlite",target,seed:true}]}).join(`
13
13
  `)}catch{return{ok:false,missing:["shared paths with an explicit target"]}}if(!(script.includes("cp -a")&&script.includes("/current/")))missing.push("adoption of existing state into shared/");if(!script.includes(`ln -sfn ${target} `))missing.push("shared paths with an explicit target");return{ok:missing.length===0,missing}}export function projectDatabaseTarget(slug,relativePath){return`/var/www/${slug}-shared/${relativePath}`}function migrateIndex(site){if(!Array.isArray(site?.preStart))return-1;return site.preStart.findIndex((cmd)=>typeof cmd==="string"&&migratesDatabase(cmd))}function migratesDatabase(command){const withoutMessages=command.replace(/'[^']*'/g,"").replace(/"[^"]*"/g,"");if(/\bmigrate\b/.test(withoutMessages))return true;return!/^\s*(?:echo|printf)\b/.test(command)&&/\bmigrate\b/.test(command)}export function applyAutomaticMigrations(sites){if(Object.values(sites).some((site)=>runsMigrations(site)))return sites;const isServerApp=(site)=>!!site&&typeof site.start==="string";const appSites=Object.entries(sites).filter(([,site])=>isServerApp(site));const owner=appSites.find(([,site])=>site?.migrateOnDeploy!==false)?.[0];if(!owner)return sites;const site=sites[owner];const preStart=Array.isArray(site.preStart)?[...site.preStart]:[];preStart.push("./buddy migrate --no-generate");return{...sites,[owner]:{...site,preStart}}}function runsMigrations(site){return migrateIndex(site)!==-1}export function applyPersistentStatePaths(sites,slug){const isServerApp=(site)=>!!site&&typeof site.start==="string";const appSites=Object.entries(sites).filter(([,site])=>isServerApp(site));const owners=new Map;for(const[name,site]of appSites){const sqlite=siteSqlitePath(site.env||{});if(!sqlite)continue;const migrates=runsMigrations(site);const previous=owners.get(sqlite);if(!previous||!previous.migrates&&migrates)owners.set(sqlite,{name,migrates})}const out={};for(const[name,site]of Object.entries(sites)){if(!isServerApp(site)){out[name]=site;continue}const sqlite=siteSqlitePath(site.env||{});const framework=["storage/logs"];if(sqlite){framework.unshift({path:sqlite,target:projectDatabaseTarget(slug,sqlite),seed:name===owners.get(sqlite)?.name})}const declared=Array.isArray(site.sharedPaths)?site.sharedPaths.filter(Boolean):[];const byPath=new Map;for(const entry of[...declared,...framework])byPath.set(typeof entry==="string"?entry:entry.path,entry);out[name]={...site,sharedPaths:[...byPath.values()]}}return out}export function encryptedEnvFileNames(projectRoot){try{return readdirSync(projectRoot).filter((name)=>/^\.env\.[\w-]+$/.test(name)&&name!==".env.example")}catch{return[]}}export function declaresScheduledWork(schedulerFile){if(!existsSync(schedulerFile))return false;const source=readFileSync(schedulerFile,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|[^:])\/\/.*$/gm,"$1");return/\bschedule\s*\.\s*(?:job|action|command|call|exec)\b/.test(source)}export function applyScheduledWork(sites,schedulerFile){if(Object.values(sites).some((site)=>site?.scheduler!==undefined))return sites;if(!declaresScheduledWork(schedulerFile))return sites;const appSites=Object.entries(sites).filter(([,site])=>typeof site?.start==="string");const owner=(appSites.find(([,site])=>runsMigrations(site))??appSites[0])?.[0];if(!owner)return sites;return{...sites,[owner]:{...sites[owner],scheduler:true}}}const apiStartPattern=/\bserve:api\b|(?:^|[\s/"'])(?:serve|storage\/framework\/runtime\/production)\/api\.[cm]?[jt]s(?=$|[\s"';&|<>()])/;function servesApi(name,site){return name==="api"||typeof site?.start==="string"&&apiStartPattern.test(site.start)}function servesHttp(site){return Boolean(site?.port||site?.domain)}function describeSiteClassification(sites){const described=Object.entries(sites).filter(([,site])=>typeof site?.start==="string").map(([name,site])=>{if(servesApi(name,site))return`\`${name}\` (api)`;if(!servesHttp(site))return`\`${name}\` (headless, no HTTP surface)`;const env=site?.env??{};const wiring=env.API_URL?"API_URL set":env.PORT_API?"PORT_API set":"no API_URL or PORT_API";return`\`${name}\` (page, ${wiring})`});return described.length>0?`Sites examined: ${described.join(", ")}.`:"No server-app sites were examined."}function isDashboardSite(name){return name==="dashboard"||name.startsWith("dashboard-")}export function apiDeploymentProblem(sites,hasApiRoutes){if(!hasApiRoutes)return;const entries=Object.entries(sites);const appSites=entries.filter(([,site])=>typeof site?.start==="string");if(appSites.length===0)return;const api=entries.find(([name,site])=>servesApi(name,site));const pages=appSites.filter(([name,site])=>!servesApi(name,site)&&!isDashboardSite(name)&&servesHttp(site));const configured=(site)=>{const env=site?.env??{};return Boolean(env.API_URL||env.PORT_API)};if(!api){if(pages.every(([,site])=>configured(site)))return;return`This project declares API routes and no site serves them. \`/api/**\` will answer 502 on every request.
14
14
  ${describeSiteClassification(sites)}
15
15
  Add an \`api\` site to config/cloud.ts running \`buddy serve:api\` on its own port, and set \`PORT_API\` on the site that serves the pages so its proxy can find it.
@@ -1 +1 @@
1
- import process from"node:process";import{log,onUnknownSubcommand}from"@stacksjs/cli";import{decryptEnv,encryptEnv,envKeyNames,getEnv,getKeypair,isValidPublicKey,publicKeyMatchesPrivateKey,resolveEnvFile,resolveEnvPrivateKey,rotateKeypair,setEnv}from"@stacksjs/env";import{ExitCode}from"@stacksjs/types";import{resolvePrivateTenants}from"../cloud-tenants";export function env(buddy){const descriptions={env:"Interact with your environment variables",get:"Get an environment variable",set:"Set an environment variable",encrypt:"Encrypt a value",decrypt:"Decrypt a value",check:"Check environment configuration and validate setup",pretty:"Pretty print the result",stdout:"Output the result to stdout",keypair:"Generate a keypair",fileKeys:"The path to the file containing the keys",excludeKey:"The key to exclude from encryption",rotate:"Rotate a keypair",rotateStdout:"Print the rotated file and its new keypair without writing either",rotateDryRun:"Report what would change without writing anything",format:"The format to output the result (json, shell, eval)",all:"Get all environment variables",file:"The environment file to use",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("env:get [key]",descriptions.get).option("-f, --file [file]",descriptions.file,{default:""}).option("--format [format]",descriptions.format,{default:"json"}).option("-a, --all",descriptions.all,{default:false}).option("-t, --pretty",descriptions.pretty,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy env:get SECRET").example("buddy env:get SECRET --file .env.production").example("buddy env:get --all --pretty").example("buddy env:get --format shell").example("buddy env:get --format eval").example("buddy env:get --format json").action(async(key,options)=>{log.debug("Running `buddy env:get` ...",options);const result=getEnv(key,{file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,all:options.all,format:options.format,prettyPrint:options.pretty});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:set [key] [value]",descriptions.set).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("--plain","Don't encrypt the value",{default:false}).option("--stdin","Read the exact value from piped standard input instead of an argument",{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy env:set SECRET=value").example("buddy env:set SECRET value").example("buddy env:set SECRET value --file .env.production").example("buddy env:set SECRET value --plain").example("buddy env:set SECRET --stdin --file .env.production").action(async(key,value,options)=>{if(!key){console.error("A key is required. Pass an empty value to clear it: `buddy env:set KEY ''`");process.exit(ExitCode.FatalError)}if(options.stdin&&value!==undefined){console.error("Choose a value argument or --stdin, not both.");process.exit(ExitCode.FatalError)}let inputValue=value;if(options.stdin){if(process.stdin.isTTY){console.error("--stdin needs a pipe or file redirection; no value was written.");process.exit(ExitCode.FatalError)}try{inputValue=await Bun.stdin.text()}catch{console.error("Could not read the value from standard input; no value was written.");process.exit(ExitCode.FatalError)}}if(inputValue===undefined){console.error(`No value given for ${key}. Pass one, or an empty string to clear it: \`buddy env:set ${key} ''\``);process.exit(ExitCode.FatalError)}log.debug("Running `buddy env:set` ...",{file:options.file,stdin:options.stdin,plain:options.plain});const result=setEnv(key,inputValue,{file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,plain:options.plain});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:encrypt [key]",descriptions.encrypt).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("-o, --stdout",descriptions.stdout,{default:false}).option("-ek, --exclude-key [excludeKey]",descriptions.excludeKey,{default:""}).example("buddy env:encrypt").example("buddy env:encrypt --file .env.production").example('buddy env:encrypt -k "SECRET_*"').action(async(key,options)=>{log.debug("Running `buddy env:encrypt` ...",options);const result=encryptEnv({file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,key,excludeKey:options.excludeKey,stdout:options.stdout});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:decrypt [key]",descriptions.decrypt).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("-o, --stdout",descriptions.stdout,{default:false}).example("buddy env:decrypt").example("buddy env:decrypt --file .env.production").example('buddy env:decrypt -k "SECRET_*"').action(async(key,options)=>{log.debug("Running `buddy env:decrypt` ...",options);const result=decryptEnv({file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,key,stdout:options.stdout});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:keypair [key]",descriptions.keypair).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("--format [format]",descriptions.format,{default:"json"}).example("buddy env:keypair").example("buddy env:keypair --file .env.production").example("buddy env:keypair DOTENV_PRIVATE_KEY").action(async(key,options)=>{log.debug("Running `buddy env:keypair` ...",options);const result=getKeypair(key,{file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,format:options.format});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:rotate [key]",descriptions.rotate).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("-o, --stdout",descriptions.rotateStdout,{default:false}).option("--dry-run",descriptions.rotateDryRun,{default:false}).option("-ek, --exclude-key [excludeKey]",descriptions.excludeKey,{default:""}).example("buddy env:rotate").example("buddy env:rotate --file .env.production").example("buddy env:rotate --file .env.production --dry-run").action(async(key,options)=>{log.debug("Running `buddy env:rotate` ...",options);const result=rotateKeypair({file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,key,excludeKey:options.excludeKey,stdout:options.stdout,dryRun:options.dryRun});if(result.success){console.log(result.output);if(result.notice)console.error(result.notice);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:check",descriptions.check).option("-f, --file [file]",descriptions.file,{default:""}).option("--strict","Require every value in a committed env file to be encrypted, not just secret-shaped ones",{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy env:check").example("buddy env:check --file .env.production").example("buddy env:check --file .env.production --strict").action(async(options)=>{log.debug("Running `buddy env:check` ...",options);const{bold,dim,green,red,yellow,intro}=await import("@stacksjs/cli");const{storage}=await import("@stacksjs/storage");const{existsSync}=await import("node:fs");const{resolve}=await import("node:path");await intro("buddy env:check");const checks=[];const envFile=resolveEnvFile(options.file,options.env)||".env";const envPath=resolve(process.cwd(),envFile);if(existsSync(envPath)){checks.push({name:`${envFile} file`,status:"pass",message:"Found"});try{const envContent=await storage.readTextFile(envPath);const contentStr=typeof envContent==="string"?envContent:envContent.data;const values=parseEnvAssignments(contentStr);const keys=Object.keys(values);const varCount=keys.length;checks.push({name:"Environment variables",status:"pass",message:`${varCount} variables defined`});const hasAppKey="APP_KEY"in values;if(hasAppKey){const appKeyValue=values.APP_KEY??"";if(appKeyValue.length>0){checks.push({name:"APP_KEY",status:"pass",message:"Set"})}else{checks.push({name:"APP_KEY",status:"warn",message:"Empty (run: buddy key:generate)"})}}else{checks.push({name:"APP_KEY",status:"warn",message:"Not found (run: buddy key:generate)"})}const{publicKeyName,privateKeyName}=envKeyNames(envFile);const privateKeyNames=[privateKeyName,"DOTENV_PRIVATE_KEY"];const publicKey=values[publicKeyName]||values.DOTENV_PUBLIC_KEY;const hasPublicKey=Boolean(publicKey);const privateKey=resolveEnvPrivateKey({file:envFile})||privateKeyNames.map((name)=>values[name]).find(Boolean);const hasPrivateKey=Boolean(privateKey);if(options.strict&&privateKey&&isValidPublicKey(publicKey)&&!publicKeyMatchesPrivateKey(publicKey,privateKey)){checks.push({name:"Encryption metadata",status:"fail",message:`The public key in ${envFile} does not match the configured private key. Restore matching metadata or run \`buddy env:rotate\` before writing encrypted values.`})}if(hasPublicKey&&hasPrivateKey){checks.push({name:"Encryption keys",status:"pass",message:"Public and private keys configured"})}else if(hasPublicKey||hasPrivateKey){checks.push({name:"Encryption keys",status:"warn",message:"Incomplete keypair (run: buddy env:keypair)"})}else{checks.push({name:"Encryption keys",status:"warn",message:"Not configured (optional)"})}const declaredTenants=await resolveDeclaredTenants();if(declaredTenants.tenants.length===0){checks.push({name:"Tenant isolation",status:"pass",message:"No tenants declared (cloud.tenants)"})}else{const{foreignTenantKeys,partitionTenantEnv}=await import("@stacksjs/env");const foreign=foreignTenantKeys(partitionTenantEnv(values,declaredTenants));const isShipped=/^\.env\.[a-z]+$/.test(envFile);const total=foreign.reduce((sum,entry)=>sum+entry.keys.length,0);if(foreign.length===0){checks.push({name:"Tenant isolation",status:"pass",message:`No foreign keys (checked ${declaredTenants.tenants.join(", ")})`})}else if(!isShipped){checks.push({name:"Tenant isolation",status:"pass",message:`${total} archived key(s) - ${envFile} is local-only and never deployed`})}else{checks.push({name:"Tenant isolation",status:"warn",message:`${total} key(s) belong to another tenant - move them to .env`});for(const{tenant,keys}of foreign){checks.push({name:` ${tenant}`,status:"warn",message:keys.join(", ")})}}}const{plaintextSecrets,trackedEnvFiles}=await import("@stacksjs/env");const tracked=trackedEnvFiles(gitLsFiles());if(!tracked.includes(envFile)){checks.push({name:"Committed secrets",status:"pass",message:`${envFile} is not committed; plaintext here stays local`})}else{let placeholders={};try{const examplePath=resolve(process.cwd(),".env.example");if(existsSync(examplePath))placeholders=parseEnvAssignments(await storage.readTextFile(examplePath).then((f)=>f.data))}catch{}const findings=plaintextSecrets(values,{placeholders,strict:options.strict});const metadata=findings.filter((finding)=>finding.reason==="invalid-public-key"||finding.reason==="private-key-material");const leaked=findings.filter((finding)=>finding.reason!=="invalid-public-key"&&finding.reason!=="private-key-material");if(metadata.length){checks.push({name:"Encryption metadata",status:"fail",message:`Unsafe encryption metadata in committed ${envFile}: ${metadata.map((finding)=>finding.key).join(", ")}. Keep private keys outside Git and restore valid public keys. For legacy keys, run \`buddy env:rotate\`.`})}if(leaked.length===0){checks.push({name:"Committed secrets",status:"pass",message:`No unencrypted secrets in ${envFile}`})}else{checks.push({name:"Committed secrets",status:"fail",message:`${leaked.length} unencrypted secret${leaked.length===1?"":"s"} in committed ${envFile}: ${leaked.map((f)=>f.key).join(", ")}. Run \`buddy env:encrypt\`, then rotate them - they are in git history.`})}}}catch(error){checks.push({name:`${envFile} content`,status:"fail",message:`Cannot read file: ${error}`})}}else{checks.push({name:`${envFile} file`,status:"fail",message:"Not found"})}const keysPath=resolve(process.cwd(),".env.keys");if(existsSync(keysPath)){checks.push({name:".env.keys file",status:"pass",message:"Found"})}else{checks.push({name:".env.keys file",status:"warn",message:"Not found (optional for encryption)"})}console.log("");console.log(bold("Environment Configuration Check:"));console.log(dim("─".repeat(60)));console.log("");let hasFailures=false;let hasWarnings=false;for(const check of checks){let statusIcon="";let statusColor=(text)=>text;if(check.status==="pass"){statusIcon="✓";statusColor=green}else if(check.status==="warn"){statusIcon="⚠";statusColor=yellow;hasWarnings=true}else{statusIcon="✗";statusColor=red;hasFailures=true}console.log(`${statusColor(statusIcon)} ${bold(check.name.padEnd(25))} ${dim(check.message)}`)}console.log("");console.log(dim("─".repeat(60)));console.log("");if(hasFailures){console.log(red("✗ Some critical checks failed. Please address the issues above."));process.exit(ExitCode.FatalError)}else if(hasWarnings){console.log(yellow("⚠ Some checks have warnings. Your environment should work but may have issues."));process.exit(ExitCode.Success)}else{console.log(green("✓ All checks passed! Your environment configuration looks healthy."));process.exit(ExitCode.Success)}});onUnknownSubcommand(buddy,"env")}async function resolveDeclaredTenants(){try{const{config}=await import("@stacksjs/config");const cloud=config.cloud;const app=config.app;return{self:app?.name,tenants:resolvePrivateTenants({declared:cloud?.tenants})}}catch{return{tenants:resolvePrivateTenants()}}}function gitLsFiles(){try{const result=Bun.spawnSync(["git","ls-files"],{cwd:process.cwd(),stdout:"pipe",stderr:"ignore"});return result.success?result.stdout.toString():""}catch{return""}}export function parseEnvAssignments(content){const values={};const assignment=/^\s*(?:export\s+)?([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i;const lines=content.split(/\r?\n/);for(let i=0;i<lines.length;i++){const line=lines[i];if(!line.trim()||line.trimStart().startsWith("#"))continue;const match=line.match(assignment);if(!match)continue;const[,key,first]=match;let raw=first.trim();const quote=raw[0]==='"'||raw[0]==="'"?raw[0]:undefined;if(quote){raw=raw.slice(1);while(!raw.endsWith(quote)&&i+1<lines.length){i++;raw+=lines[i]}raw=raw.endsWith(quote)?raw.slice(0,-1):raw}else{raw=raw.replace(/\s+#.*$/,"").trim()}values[key]=raw}return values}
1
+ import process from"node:process";import{log,onUnknownSubcommand}from"@stacksjs/cli";import{decryptEnv,encryptEnv,envKeyNames,getEnv,getKeypair,isValidPublicKey,publicKeyMatchesPrivateKey,resolveEnvFile,resolveEnvPrivateKey,rotateKeypair,setEnv}from"@stacksjs/env";import{ExitCode}from"@stacksjs/types";import{resolvePrivateTenants}from"../cloud-tenants";export function env(buddy){const descriptions={env:"Interact with your environment variables",get:"Get an environment variable",set:"Set an environment variable",encrypt:"Encrypt a value",decrypt:"Decrypt a value",check:"Check environment configuration and validate setup",pretty:"Pretty print the result",stdout:"Output the result to stdout",keypair:"Generate a keypair",fileKeys:"The path to the file containing the keys",excludeKey:"The key to exclude from encryption",rotate:"Rotate a keypair",rotateStdout:"Print the rotated file and its new keypair without writing either",rotateDryRun:"Report what would change without writing anything",format:"The format to output the result (json, shell, eval)",all:"Get all environment variables",file:"The environment file to use",project:"Target a specific project",verbose:"Enable verbose output"};buddy.command("env:get [key]",descriptions.get).option("-f, --file [file]",descriptions.file,{default:""}).option("--format [format]",descriptions.format,{default:"json"}).option("-a, --all",descriptions.all,{default:false}).option("-t, --pretty",descriptions.pretty,{default:false}).option("-p, --project [project]",descriptions.project,{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy env:get SECRET").example("buddy env:get SECRET --file .env.production").example("buddy env:get --all --pretty").example("buddy env:get --format shell").example("buddy env:get --format eval").example("buddy env:get --format json").action(async(key,options)=>{log.debug("Running `buddy env:get` ...",options);const result=getEnv(key,{file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,all:options.all,format:options.format,prettyPrint:options.pretty});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:set [key] [value]",descriptions.set).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("--plain","Don't encrypt the value",{default:false}).option("--stdin","Read the exact value from piped standard input instead of an argument",{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy env:set SECRET=value").example("buddy env:set SECRET value").example("buddy env:set SECRET value --file .env.production").example("buddy env:set SECRET value --plain").example("buddy env:set SECRET --stdin --file .env.production").action(async(key,value,options)=>{if(!key){console.error("A key is required. Pass an empty value to clear it: `buddy env:set KEY ''`");process.exit(ExitCode.FatalError)}if(options.stdin&&value!==undefined){console.error("Choose a value argument or --stdin, not both.");process.exit(ExitCode.FatalError)}let inputValue=value;if(options.stdin){if(process.stdin.isTTY){console.error("--stdin needs a pipe or file redirection; no value was written.");process.exit(ExitCode.FatalError)}try{inputValue=await Bun.stdin.text()}catch{console.error("Could not read the value from standard input; no value was written.");process.exit(ExitCode.FatalError)}}if(inputValue===undefined){console.error(`No value given for ${key}. Pass one, or an empty string to clear it: \`buddy env:set ${key} ''\``);process.exit(ExitCode.FatalError)}log.debug("Running `buddy env:set` ...",{file:options.file,stdin:options.stdin,plain:options.plain});const result=setEnv(key,inputValue,{file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,plain:options.plain});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:encrypt [key]",descriptions.encrypt).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("-o, --stdout",descriptions.stdout,{default:false}).option("-ek, --exclude-key [excludeKey]",descriptions.excludeKey,{default:""}).example("buddy env:encrypt").example("buddy env:encrypt --file .env.production").example('buddy env:encrypt -k "SECRET_*"').action(async(key,options)=>{log.debug("Running `buddy env:encrypt` ...",options);const result=encryptEnv({file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,key,excludeKey:options.excludeKey,stdout:options.stdout});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:decrypt [key]",descriptions.decrypt).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("-o, --stdout",descriptions.stdout,{default:false}).example("buddy env:decrypt").example("buddy env:decrypt --file .env.production").example('buddy env:decrypt -k "SECRET_*"').action(async(key,options)=>{log.debug("Running `buddy env:decrypt` ...",options);const result=decryptEnv({file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,key,stdout:options.stdout});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:keypair [key]",descriptions.keypair).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("--format [format]",descriptions.format,{default:"json"}).example("buddy env:keypair").example("buddy env:keypair --file .env.production").example("buddy env:keypair DOTENV_PRIVATE_KEY").action(async(key,options)=>{log.debug("Running `buddy env:keypair` ...",options);const result=getKeypair(key,{file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,format:options.format});if(result.success){console.log(result.output);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:rotate [key]",descriptions.rotate).option("-f, --file [file]",descriptions.file,{default:""}).option("-fk, --file-keys [fileKeys]",descriptions.fileKeys,{default:""}).option("-o, --stdout",descriptions.rotateStdout,{default:false}).option("--dry-run",descriptions.rotateDryRun,{default:false}).option("-ek, --exclude-key [excludeKey]",descriptions.excludeKey,{default:""}).example("buddy env:rotate").example("buddy env:rotate --file .env.production").example("buddy env:rotate --file .env.production --dry-run").action(async(key,options)=>{log.debug("Running `buddy env:rotate` ...",options);const result=rotateKeypair({file:resolveEnvFile(options.file,options.env),keysFile:options.fileKeys,key,excludeKey:options.excludeKey,stdout:options.stdout,dryRun:options.dryRun});if(result.success){console.log(result.output);if(result.notice)console.error(result.notice);process.exit(ExitCode.Success)}else{console.error(result.error);process.exit(ExitCode.FatalError)}});buddy.command("env:check",descriptions.check).option("-f, --file [file]",descriptions.file,{default:""}).option("--strict","Require every value in a committed env file to be encrypted, not just secret-shaped ones",{default:false}).option("--verbose",descriptions.verbose,{default:false}).example("buddy env:check").example("buddy env:check --file .env.production").example("buddy env:check --file .env.production --strict").action(async(options)=>{log.debug("Running `buddy env:check` ...",options);const{bold,dim,green,red,yellow,intro}=await import("@stacksjs/cli");const{storage}=await import("@stacksjs/storage");const{existsSync}=await import("node:fs");const{resolve}=await import("node:path");await intro("buddy env:check");const checks=[];const envFile=resolveEnvFile(options.file,options.env)||".env";const envPath=resolve(process.cwd(),envFile);if(existsSync(envPath)){checks.push({name:`${envFile} file`,status:"pass",message:"Found"});try{const envContent=await storage.readTextFile(envPath);const contentStr=typeof envContent==="string"?envContent:envContent.data;const values=parseEnvAssignments(contentStr);const keys=Object.keys(values);const varCount=keys.length;checks.push({name:"Environment variables",status:"pass",message:`${varCount} variables defined`});const hasAppKey="APP_KEY"in values;if(hasAppKey){const appKeyValue=values.APP_KEY??"";if(appKeyValue.length>0){checks.push({name:"APP_KEY",status:"pass",message:"Set"})}else{checks.push({name:"APP_KEY",status:"warn",message:"Empty (run: buddy key:generate)"})}}else{checks.push({name:"APP_KEY",status:"warn",message:"Not found (run: buddy key:generate)"})}const{publicKeyName,privateKeyName}=envKeyNames(envFile);const privateKeyNames=[privateKeyName,"DOTENV_PRIVATE_KEY"];const publicKey=values[publicKeyName]||values.DOTENV_PUBLIC_KEY;const hasPublicKey=Boolean(publicKey);const privateKey=resolveEnvPrivateKey({file:envFile})||privateKeyNames.map((name)=>values[name]).find(Boolean);const hasPrivateKey=Boolean(privateKey);if(options.strict&&privateKey&&isValidPublicKey(publicKey)&&!publicKeyMatchesPrivateKey(publicKey,privateKey)){checks.push({name:"Encryption metadata",status:"fail",message:`The public key in ${envFile} does not match the configured private key. Restore matching metadata or run \`buddy env:rotate\` before writing encrypted values.`})}if(hasPublicKey&&hasPrivateKey){checks.push({name:"Encryption keys",status:"pass",message:"Public and private keys configured"})}else if(hasPublicKey||hasPrivateKey){checks.push({name:"Encryption keys",status:"warn",message:"Incomplete keypair (run: buddy env:keypair)"})}else{checks.push({name:"Encryption keys",status:"warn",message:"Not configured (optional)"})}const declaredTenants=await resolveDeclaredTenants();if(declaredTenants.tenants.length===0){checks.push({name:"Tenant isolation",status:"pass",message:"No tenants declared (cloud.tenants)"})}else{const{foreignTenantKeys,partitionTenantEnv}=await import("@stacksjs/env");const{HQ_CONNECTION_ENV_KEYS}=await import("../hq");const foreign=foreignTenantKeys(partitionTenantEnv(values,{...declaredTenants,shared:HQ_CONNECTION_ENV_KEYS}));const isShipped=/^\.env\.[a-z]+$/.test(envFile);const total=foreign.reduce((sum,entry)=>sum+entry.keys.length,0);if(foreign.length===0){checks.push({name:"Tenant isolation",status:"pass",message:`No foreign keys (checked ${declaredTenants.tenants.join(", ")})`})}else if(!isShipped){checks.push({name:"Tenant isolation",status:"pass",message:`${total} archived key(s) - ${envFile} is local-only and never deployed`})}else{checks.push({name:"Tenant isolation",status:"warn",message:`${total} key(s) belong to another tenant - move them to .env`});for(const{tenant,keys}of foreign){checks.push({name:` ${tenant}`,status:"warn",message:keys.join(", ")})}}}const{plaintextSecrets,trackedEnvFiles}=await import("@stacksjs/env");const tracked=trackedEnvFiles(gitLsFiles());if(!tracked.includes(envFile)){checks.push({name:"Committed secrets",status:"pass",message:`${envFile} is not committed; plaintext here stays local`})}else{let placeholders={};try{const examplePath=resolve(process.cwd(),".env.example");if(existsSync(examplePath))placeholders=parseEnvAssignments(await storage.readTextFile(examplePath).then((f)=>f.data))}catch{}const findings=plaintextSecrets(values,{placeholders,strict:options.strict});const metadata=findings.filter((finding)=>finding.reason==="invalid-public-key"||finding.reason==="private-key-material");const leaked=findings.filter((finding)=>finding.reason!=="invalid-public-key"&&finding.reason!=="private-key-material");if(metadata.length){checks.push({name:"Encryption metadata",status:"fail",message:`Unsafe encryption metadata in committed ${envFile}: ${metadata.map((finding)=>finding.key).join(", ")}. Keep private keys outside Git and restore valid public keys. For legacy keys, run \`buddy env:rotate\`.`})}if(leaked.length===0){checks.push({name:"Committed secrets",status:"pass",message:`No unencrypted secrets in ${envFile}`})}else{checks.push({name:"Committed secrets",status:"fail",message:`${leaked.length} unencrypted secret${leaked.length===1?"":"s"} in committed ${envFile}: ${leaked.map((f)=>f.key).join(", ")}. Run \`buddy env:encrypt\`, then rotate them - they are in git history.`})}}}catch(error){checks.push({name:`${envFile} content`,status:"fail",message:`Cannot read file: ${error}`})}}else{checks.push({name:`${envFile} file`,status:"fail",message:"Not found"})}const keysPath=resolve(process.cwd(),".env.keys");if(existsSync(keysPath)){checks.push({name:".env.keys file",status:"pass",message:"Found"})}else{checks.push({name:".env.keys file",status:"warn",message:"Not found (optional for encryption)"})}console.log("");console.log(bold("Environment Configuration Check:"));console.log(dim("─".repeat(60)));console.log("");let hasFailures=false;let hasWarnings=false;for(const check of checks){let statusIcon="";let statusColor=(text)=>text;if(check.status==="pass"){statusIcon="✓";statusColor=green}else if(check.status==="warn"){statusIcon="⚠";statusColor=yellow;hasWarnings=true}else{statusIcon="✗";statusColor=red;hasFailures=true}console.log(`${statusColor(statusIcon)} ${bold(check.name.padEnd(25))} ${dim(check.message)}`)}console.log("");console.log(dim("─".repeat(60)));console.log("");if(hasFailures){console.log(red("✗ Some critical checks failed. Please address the issues above."));process.exit(ExitCode.FatalError)}else if(hasWarnings){console.log(yellow("⚠ Some checks have warnings. Your environment should work but may have issues."));process.exit(ExitCode.Success)}else{console.log(green("✓ All checks passed! Your environment configuration looks healthy."));process.exit(ExitCode.Success)}});onUnknownSubcommand(buddy,"env")}async function resolveDeclaredTenants(){try{const{config}=await import("@stacksjs/config");const cloud=config.cloud;const app=config.app;return{self:app?.name,tenants:resolvePrivateTenants({declared:cloud?.tenants})}}catch{return{tenants:resolvePrivateTenants()}}}function gitLsFiles(){try{const result=Bun.spawnSync(["git","ls-files"],{cwd:process.cwd(),stdout:"pipe",stderr:"ignore"});return result.success?result.stdout.toString():""}catch{return""}}export function parseEnvAssignments(content){const values={};const assignment=/^\s*(?:export\s+)?([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i;const lines=content.split(/\r?\n/);for(let i=0;i<lines.length;i++){const line=lines[i];if(!line.trim()||line.trimStart().startsWith("#"))continue;const match=line.match(assignment);if(!match)continue;const[,key,first]=match;let raw=first.trim();const quote=raw[0]==='"'||raw[0]==="'"?raw[0]:undefined;if(quote){raw=raw.slice(1);while(!raw.endsWith(quote)&&i+1<lines.length){i++;raw+=lines[i]}raw=raw.endsWith(quote)?raw.slice(0,-1):raw}else{raw=raw.replace(/\s+#.*$/,"").trim()}values[key]=raw}return values}
@@ -1,11 +1 @@
1
- /**
2
- * Why this deploy leaves queued jobs with nothing to run them, phrased as the
3
- * fix. Returns undefined when a worker is declared or jobs do not queue.
4
- *
5
- * In production the framework queues every dispatched job, to the database
6
- * unless QUEUE_DRIVER says redis, and it refuses `sync`. The framework's own
7
- * actions dispatch jobs in every app (a password reset email is one), so an
8
- * app that declares no worker has mail that is accepted and never sent. That
9
- * fails silently by design at the call site, which is why it is said here.
10
- */
11
1
  export declare function missingQueueWorkerProblem(sites: Record<string, any> | undefined, queueDriver: string | undefined): string | undefined;
@@ -1 +1 @@
1
- export function missingQueueWorkerProblem(sites,queueDriver){const all=Object.values(sites??{}).filter(Boolean);if(!all.some((site)=>site.start||site.port))return;const worked=all.some((site)=>Array.isArray(site.queues)&&site.queues.length>0||Array.isArray(site.daemons)&&site.daemons.some((daemon)=>/queue[:-]work|queue-worker/.test(String(daemon?.command??""))));if(worked)return;const driver=queueDriver||"database";return`No site declares a queue worker, and in production jobs are queued (QUEUE_DRIVER=${driver}): anything the app dispatches, password reset and other framework emails included, will be accepted and never run. `+`Add \`queues: [{ connection: '${driver}', queue: 'emails,default' }]\` to a site in config/cloud.ts${driver==="database"?", and `buddy queue:table` after `migrate` in its preStart.":"."}`}
1
+ const QUEUE_WORKER_COMMAND=/queue[:-]work|queue-worker/;export function missingQueueWorkerProblem(sites,queueDriver){const all=Object.values(sites??{}).filter(Boolean);const served=all.filter((site)=>site.start||site.port);if(served.length===0)return;if(served.every((site)=>site.env?.STACKS_DEFAULT_ROUTES==="none"))return;const worked=all.some((site)=>Array.isArray(site.queues)&&site.queues.length>0||QUEUE_WORKER_COMMAND.test(String(site.start??""))||Array.isArray(site.daemons)&&site.daemons.some((daemon)=>QUEUE_WORKER_COMMAND.test(String(daemon?.command??""))));if(worked)return;const driver=queueDriver==="redis"?"redis":"database";return`No site declares a queue worker, and in production jobs are queued (to ${driver==="redis"?"redis":"the database"}): anything the app dispatches, password reset and other framework emails included, will be accepted and never run. `+`Add \`queues: [{ connection: '${driver}', queue: 'emails,default' }]\` to a site in config/cloud.ts${driver==="database"?", and `buddy queue:table` after `migrate` in its preStart.":"."}`}
package/dist/hq.d.ts CHANGED
@@ -59,6 +59,16 @@ export declare function runSupportDoctor(config: HqServicesConfig, deps: Pick<Hq
59
59
  */
60
60
  export declare const HQ_SERVICES: Record<HqServiceName, HqServiceDescriptor>;
61
61
  export declare const HQ_SERVICE_NAMES: HqServiceName[];
62
+ /**
63
+ * Every env key that is an app's connection to an HQ service: the keys
64
+ * `hq:connect` writes, and the settings config/services.ts, config/logging.ts
65
+ * and config/monitoring.ts read beside them.
66
+ *
67
+ * They are the app's own, even on a box where the service is a tenant too. A
68
+ * deploy keeps a tenant's prefixed keys out of other projects' sites, and
69
+ * without this list it took an app's `BUGHQ_KEY` for BugHQ's own secret.
70
+ */
71
+ export declare const HQ_CONNECTION_ENV_KEYS: readonly string[];
62
72
  /** The services `hq:connect` asks when none is named: the two that have shipped the contract. */
63
73
  export declare const HQ_DEFAULT_SERVICES: HqServiceName[];
64
74
  /**
package/dist/hq.js CHANGED
@@ -1 +1 @@
1
- import{createHqClient}from"@stacksjs/hq/client";export const HQ_SERVICES={bughq:{label:"BugHQ",env:{key:"BUGHQ_KEY",readKey:"BUGHQ_READ_KEY",project:"BUGHQ_PROJECT_ID"},verify:"error"},loghq:{label:"LogHQ",env:{key:"LOGHQ_KEY",readKey:"LOGHQ_READ_KEY",project:"LOGHQ_PROJECT_ID"},verify:"log"},analyticshq:{label:"AnalyticsHQ",env:{readKey:"ANALYTICSHQ_READ_KEY",project:"ANALYTICSHQ_SITE_ID"}},statushq:{label:"StatusHQ",env:{key:"STATUSHQ_KEY",readKey:"STATUSHQ_READ_KEY"}},supporthq:{label:"HQ.support",env:{key:"SUPPORTHQ_KEY",readKey:"SUPPORTHQ_READ_KEY",project:"SUPPORTHQ_PROJECT_ID"},verify:"support"},commshq:{label:"CommsHQ",env:{key:"COMMSHQ_KEY",readKey:"COMMSHQ_READ_KEY"}},reportshq:{label:"ReportsHQ",env:{license:"REPORTSHQ_LICENSE"}}};export const HQ_SERVICE_NAMES=Object.keys(HQ_SERVICES);export const HQ_DEFAULT_SERVICES=["bughq","loghq"];const REQUEST_TIMEOUT_MS=1e4;function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function origin(url){return url.replace(/\/+$/,"")}function httpUrl(value,base){if(typeof value!=="string"||!value)return null;try{const url=new URL(value,base);return url.protocol==="https:"||url.protocol==="http:"?url.toString():null}catch{return null}}function toGrant(body,base,licensed){const project=body.project;if(!isRecord(project)||project.id==null)return null;if(licensed){if(typeof body.licenseKey!=="string"||!body.licenseKey)return null;return{project:{id:String(project.id),name:String(project.name??project.id)},ingestKey:"",readKey:"",licenseKey:body.licenseKey,dashboardUrl:httpUrl(body.dashboardUrl,base)??""}}if(typeof body.ingestKey!=="string"||typeof body.readKey!=="string")return null;if(!body.ingestKey||!body.readKey)return null;return{project:{id:String(project.id),name:String(project.name??project.id)},ingestKey:body.ingestKey,readKey:body.readKey,dashboardUrl:httpUrl(body.dashboardUrl,base)??""}}async function request(deps,url,init={}){const signals=[AbortSignal.timeout(REQUEST_TIMEOUT_MS),...deps.signal?[deps.signal]:[]];try{return await deps.fetch(url,{...init,signal:AbortSignal.any(signals)})}catch{return null}}function retryAfterMs(response,fallback){const seconds=Number(response.headers.get("retry-after"));return Number.isFinite(seconds)&&seconds>0?Math.min(seconds,60)*1000:fallback}export function resolveHqServices(requested,fallback=HQ_DEFAULT_SERVICES){const names=requested.map((name)=>name.trim().toLowerCase()).filter(Boolean);if(!names.length)return{services:[...fallback]};const unknown=names.filter((name)=>!(name in HQ_SERVICES));if(unknown.length)return{error:`Unknown service: ${unknown.join(", ")}. Choose from ${HQ_SERVICE_NAMES.join(", ")}.`};return{services:[...new Set(names)]}}async function connectOne(service,url,options,deps){const{label}=HQ_SERVICES[service];const base=origin(url);const outcome=(status,detail)=>({outcome:{service,status,detail,send:"skipped",read:"skipped"}});const started=await request(deps,`${base}/api/cli/connect`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({app:options.app})});if(deps.signal?.aborted)return outcome("cancelled","cancelled");if(!started)return outcome("unreachable",`could not reach ${base}`);if(started.status===404||started.status===405)return outcome("unavailable","not available yet");if(started.status===429)return outcome("failed","too many requests, try again in a minute");if(!started.ok)return outcome("failed",`the service answered ${started.status}`);const body=await started.json().catch(()=>null);const code=isRecord(body)&&typeof body.code==="string"&&/^[\w-]{16,128}$/.test(body.code)?body.code:null;const approveUrl=isRecord(body)?httpUrl(body.approveUrl,base):null;if(!code||!approveUrl)return outcome("failed","the service answered something that is not a connect code");const confirmCode=isRecord(body)&&typeof body.confirmCode==="string"&&/^[\w-]{1,32}$/.test(body.confirmCode)?body.confirmCode:null;deps.print("");deps.print(`${label}: approve this connection in your browser`);deps.print(` ${approveUrl}`);if(confirmCode)deps.print(` Confirmation code: ${confirmCode} (type it on that page)`);deps.print(" If the page asks you to sign in, sign in and open the link again.");deps.print(" Waiting for approval. Press Ctrl+C to cancel.");if(options.open!==false){try{await deps.open(approveUrl)}catch{}}const interval=options.pollIntervalMs??2000;const deadline=deps.now()+(options.timeoutMs??10*60*1000);const pollUrl=`${base}/api/cli/connect/${encodeURIComponent(code)}`;while(true){if(deps.signal?.aborted)return outcome("cancelled","cancelled");if(deps.now()>=deadline)return outcome("timeout","nobody approved it in time");await deps.sleep(Math.min(interval,Math.max(0,deadline-deps.now())),deps.signal);if(deps.signal?.aborted)return outcome("cancelled","cancelled");const polled=await request(deps,pollUrl,{headers:{Accept:"application/json"}});if(!polled)continue;if(polled.status===429){await deps.sleep(retryAfterMs(polled,interval),deps.signal);continue}if(polled.status===404)return outcome("expired","the request expired, run the command again");if(!polled.ok)return outcome("failed",`the service answered ${polled.status}`);const answer=await polled.json().catch(()=>null);if(!isRecord(answer)||answer.status==="pending")continue;if(answer.status==="expired")return outcome("expired","the request expired, run the command again");const grant=toGrant(answer,base,Boolean(HQ_SERVICES[service].env.license));if(!grant)return outcome("failed","the service approved the request without sending keys");return{grant,outcome:{service,status:"connected",project:grant.project.name,dashboardUrl:grant.dashboardUrl||undefined,send:"skipped",read:"skipped"}}}}function envEntries(service,grant){const names=HQ_SERVICES[service].env;const entries={};if(names.license&&grant.licenseKey)return{[names.license]:grant.licenseKey};if(names.key)entries[names.key]=grant.ingestKey;if(names.readKey)entries[names.readKey]=grant.readKey;if(names.project)entries[names.project]=grant.project.id;return entries}async function verify(service,url,grant,options,deps){const kind=HQ_SERVICES[service].verify;if(!kind)return{send:"skipped",read:"skipped"};const base=origin(url);if(kind==="support"){const client=createHqClient({services:{supporthq:{url:base,readKey:grant.readKey,project:grant.project.id}},fetch:deps.fetch});const result=await client.support.conversations({limit:1});return result.ok?{send:"skipped",read:"pass"}:{send:"skipped",read:"fail",detail:describeUnavailable(result)}}const marker=`hq-connect-${crypto.randomUUID().slice(0,8)}`;const message=`buddy hq:connect test ${marker}`;const timestamp=new Date(deps.now()).toISOString();const sent=kind==="log"?await request(deps,`${base}/logs`,{method:"POST",headers:{"Content-Type":"application/json","X-LogHQ-Key":grant.ingestKey},body:JSON.stringify({logs:[{level:"info",message,timestamp,context:{source:"buddy hq:connect"}}]})}):await request(deps,`${base}/errors`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:grant.ingestKey,type:"HqConnectTest",message,level:"info",environment:"hq-connect",timestamp,sdk:{name:"buddy.hq-connect"}})});if(!sent?.ok)return{send:"fail",read:"skipped",detail:sent?`sending the test ${kind} answered ${sent.status}`:`sending the test ${kind} did not get through`};const receipt=await sent.json().catch(()=>null);if(isRecord(receipt)&&(receipt.sampled===true||receipt.stored===0))return{send:"pass",read:"skipped",detail:`the plan allowance is used up, so the test ${kind} was not kept`};const client=createHqClient({services:{[service]:{url:base,readKey:grant.readKey,project:grant.project.id}},timeoutMs:REQUEST_TIMEOUT_MS,fetch:(input,init)=>deps.fetch(input,init)});let reason=`the test ${kind} was accepted but did not show up`;const attempts=options.readAttempts??5;for(let attempt=0;attempt<attempts;attempt++){if(attempt>0)await deps.sleep(1000,deps.signal);if(deps.signal?.aborted)return{send:"pass",read:"fail",detail:"cancelled"};if(kind==="log"){const page=await client.logs.list({search:marker,limit:5});if(page.ok&&page.data.logs.some((log)=>log.message.includes(marker)))return{send:"pass",read:"pass"};if(!page.ok)reason=describeUnavailable(page)}else{const list=await client.issues.list();if(list.ok&&list.data.some((issue)=>issue.title.includes(marker)))return{send:"pass",read:"pass"};if(!list.ok)reason=describeUnavailable(list)}}return{send:"pass",read:"fail",detail:reason}}export function describeUnavailable(result){switch(result.reason){case"not_configured":return"not connected";case"unauthorized":return"the read key was refused";case"timeout":return"the service did not answer in time";case"network":return"the service could not be reached";case"http":return result.status===404?"not available yet":`the service answered ${result.status}`;case"bad_response":return"the service answered something unexpected"}}export function renderTable(headers,rows){const widths=headers.map((header,column)=>Math.max(header.length,...rows.map((row)=>(row[column]??"").length)));const line=(cells)=>cells.map((cell,column)=>(cell??"").padEnd(widths[column])).join(" ").trimEnd();return[line(headers),line(widths.map((width)=>"-".repeat(width))),...rows.map(line)]}const CONNECT_WORDS={connected:"pass",unavailable:"not available yet",unreachable:"fail",expired:"fail",timeout:"fail",cancelled:"cancelled",failed:"fail"};const CHECK_WORDS={pass:"pass",fail:"fail",skipped:"-"};export function connectTable(outcomes){return renderTable(["Service","Connect","Send","Read back","Note"],outcomes.map((outcome)=>[HQ_SERVICES[outcome.service].label,CONNECT_WORDS[outcome.status],CHECK_WORDS[outcome.send],CHECK_WORDS[outcome.read],outcome.status==="unavailable"?"":outcome.detail??""]))}export async function runHqConnect(services,config,options,deps){const outcomes=[];for(const service of services){const{label}=HQ_SERVICES[service];if(deps.signal?.aborted){outcomes.push({service,status:"cancelled",detail:"cancelled",send:"skipped",read:"skipped"});continue}const url=config[service]?.url;if(!url){outcomes.push({service,status:"failed",detail:"no URL is configured in config/services.ts",send:"skipped",read:"skipped"});continue}const{outcome,grant}=await connectOne(service,url,options,deps);if(!grant){if(outcome.status==="unavailable")deps.print(`${label}: not available yet`);else if(outcome.status!=="cancelled")deps.print(`${label}: not connected (${outcome.detail})`);outcomes.push(outcome);continue}try{await deps.writeEnv(envEntries(service,grant))}catch(error){const why=error instanceof Error?error.message:"unknown error";deps.print(`${label}: approved, but the keys could not be written to .env (${why})`);outcomes.push({...outcome,status:"failed",detail:"the keys could not be written to .env"});continue}deps.print(grant.licenseKey?`${label}: licensed "${grant.project.name}". Licence written to .env.`:`${label}: connected to project "${grant.project.name}". Keys written to .env.`);if(grant.dashboardUrl)deps.print(` Dashboard: ${grant.dashboardUrl}`);if(options.verify===false){outcomes.push(outcome);continue}outcomes.push({...outcome,...await verify(service,url,grant,options,deps)})}if(deps.signal?.aborted)deps.print("Cancelled. Services already connected keep their keys.");deps.print("");for(const line of connectTable(outcomes))deps.print(line);const ok=outcomes.every((outcome)=>outcome.status==="unavailable"||outcome.status==="connected"&&outcome.send!=="fail"&&outcome.read!=="fail");return{outcomes,ok}}const count=(value)=>value.toLocaleString("en-US");const REPORTSHQ_LICENSE=/^rhq_lic_[0-9a-f]{32}$/;export function describeReportsHqLicense(license){if(!license)return"unlicensed. Reports work in full; set REPORTSHQ_LICENSE to remove the notice";return REPORTSHQ_LICENSE.test(license)?"licensed (checked offline, nothing is metered)":"the licence key is not in the expected format. Reports are unaffected"}export async function runHqStatus(config,deps,services=HQ_SERVICE_NAMES){const connected=services.filter((service)=>config[service]?.url&&config[service]?.readKey);const license=services.includes("reportshq")?config.reportshq?.license:undefined;if(!connected.length&&!license){deps.print("No HQ service is connected yet. Run `buddy hq:connect` to connect one.");return[]}const client=createHqClient({services:Object.fromEntries(connected.map((service)=>[service,{url:config[service].url,readKey:config[service].readKey}])),timeoutMs:REQUEST_TIMEOUT_MS,fetch:(input,init)=>deps.fetch(input,init)});const rows=[];for(const[index,usage]of(await Promise.all(connected.map((service)=>client.getUsage(service)))).entries()){const service=connected[index];if(!usage.ok){rows.push({service,unavailable:describeUnavailable(usage)});continue}if(!usage.data.length)rows.push({service,unavailable:"no meters reported"});for(const report of usage.data){const over=report.limit!==null&&report.limit>0&&report.used/report.limit>=0.8;rows.push({service,meter:report.meter,used:report.used,limit:report.limit,period:report.period,state:report.state,...over?{upgradeUrl:report.upgradeUrl}:{}})}}if(license)rows.push({service:"reportshq",unavailable:describeReportsHqLicense(license)});const table=renderTable(["Service","Meter","Used","Limit","Period","State"],rows.map((row)=>row.unavailable?[HQ_SERVICES[row.service].label,row.unavailable]:[HQ_SERVICES[row.service].label,row.meter,count(row.used),row.limit===null?"unlimited":count(row.limit),row.period,row.state]));for(const line of table)deps.print(line);const upgrades=rows.filter((row)=>row.upgradeUrl);if(upgrades.length)deps.print("");for(const row of upgrades){const percent=Math.round(row.used/row.limit*100);deps.print(`${HQ_SERVICES[row.service].label} ${row.meter} is at ${percent}% of its allowance. Upgrade: ${row.upgradeUrl}`)}return rows}export async function runSupportDoctor(config,deps,options={}){const service=config.supporthq;const configured=Boolean(service?.url&&service.key&&service.readKey&&service.project);const checks=[{name:"configuration",ok:configured,detail:configured?"server key, read key and project configured":"missing configuration; run `buddy support:install`"}];if(configured){const client=createHqClient({services:{supporthq:{url:service.url,readKey:service.readKey,project:service.project}},fetch:deps.fetch});const usage=await client.getUsage("supporthq");checks.push({name:"usage",ok:usage.ok,detail:usage.ok?`${usage.data.length} usage meters readable`:describeUnavailable(usage)});const conversations=await client.support.conversations({limit:1});checks.push({name:"conversations",ok:conversations.ok,detail:conversations.ok?"project summaries readable":describeUnavailable(conversations)});if(service?.enabled===true){try{const target=new URL(service.url);if(target.username||target.password||target.search||target.hash||target.pathname!=="/"||target.protocol!=="https:"&&!(target.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(target.hostname)))throw new Error("Invalid support origin");const base=target.origin;const probe=await deps.fetch(`${base}/api/v1/projects/${encodeURIComponent(service.project)}/installation`,{headers:{Authorization:`Bearer ${service.key}`},redirect:"error",signal:AbortSignal.timeout(1e4)});const body=probe.ok?await probe.json():null;const current=new URL(options.origin||"").origin;const accepted=isRecord(body)&&body.service==="supporthq"&&body.protocol===1&&body.project===service.project&&body.buddyConnected===true&&Array.isArray(body.allowedOrigins)&&body.allowedOrigins.includes(current);checks.push({name:"installation",ok:accepted,detail:accepted?"approved project and exact app origin; no customer probe was created":"native installation or app origin is not approved"})}catch{checks.push({name:"installation",ok:false,detail:"native installation could not be read"})}if(service.messenger?.enabled){try{const loader=new URL(service.messenger.loaderUrl||"https://hq.support/support.js");if(loader.username||loader.password||loader.search||loader.hash||loader.protocol!=="https:"&&!(loader.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(loader.hostname)))throw new Error("Invalid loader");const response=await deps.fetch(new URL("/widgets/manifest.json",loader).href,{redirect:"error",signal:AbortSignal.timeout(1e4)});const manifest=response.ok?await response.json():null;const published=isRecord(manifest)&&manifest.schemaVersion===1&&Array.isArray(manifest.files)&&manifest.files.some((file)=>isRecord(file)&&typeof file.path==="string"&&file.path.endsWith("/bundle.js")&&typeof file.sha256==="string"&&/^[a-f0-9]{64}$/.test(file.sha256)&&typeof file.gzipBytes==="number"&&file.gzipBytes>0&&file.gzipBytes<=1e5);checks.push({name:"widget",ok:published,detail:published?"published manifest reports a versioned widget within the initial code budget":"published widget manifest or size budget is unavailable"})}catch{checks.push({name:"widget",ok:false,detail:"published widget could not be checked"})}}}}for(const check of checks)deps.print(`HQ.support ${check.name}: ${check.ok?"pass":"fail"} (${check.detail})`);return{ok:checks.every((check)=>check.ok),checks}}
1
+ import{createHqClient}from"@stacksjs/hq/client";export const HQ_SERVICES={bughq:{label:"BugHQ",env:{key:"BUGHQ_KEY",readKey:"BUGHQ_READ_KEY",project:"BUGHQ_PROJECT_ID"},verify:"error"},loghq:{label:"LogHQ",env:{key:"LOGHQ_KEY",readKey:"LOGHQ_READ_KEY",project:"LOGHQ_PROJECT_ID"},verify:"log"},analyticshq:{label:"AnalyticsHQ",env:{readKey:"ANALYTICSHQ_READ_KEY",project:"ANALYTICSHQ_SITE_ID"}},statushq:{label:"StatusHQ",env:{key:"STATUSHQ_KEY",readKey:"STATUSHQ_READ_KEY"}},supporthq:{label:"HQ.support",env:{key:"SUPPORTHQ_KEY",readKey:"SUPPORTHQ_READ_KEY",project:"SUPPORTHQ_PROJECT_ID"},verify:"support"},commshq:{label:"CommsHQ",env:{key:"COMMSHQ_KEY",readKey:"COMMSHQ_READ_KEY"}},reportshq:{label:"ReportsHQ",env:{license:"REPORTSHQ_LICENSE"}}};export const HQ_SERVICE_NAMES=Object.keys(HQ_SERVICES);export const HQ_CONNECTION_ENV_KEYS=[...new Set([...Object.values(HQ_SERVICES).flatMap((service)=>Object.values(service.env)),"BUGHQ_HOST","BUGHQ_DSN","BUGHQ_PROJECT","BUGHQ_RELEASE","LOGHQ_BASE_URL","LOGHQ_PROJECT","ANALYTICSHQ_URL","STATUSHQ_URL","SUPPORTHQ_URL","COMMSHQ_URL","REPORTSHQ_URL"])];export const HQ_DEFAULT_SERVICES=["bughq","loghq"];const REQUEST_TIMEOUT_MS=1e4;function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function origin(url){return url.replace(/\/+$/,"")}function httpUrl(value,base){if(typeof value!=="string"||!value)return null;try{const url=new URL(value,base);return url.protocol==="https:"||url.protocol==="http:"?url.toString():null}catch{return null}}function toGrant(body,base,licensed){const project=body.project;if(!isRecord(project)||project.id==null)return null;if(licensed){if(typeof body.licenseKey!=="string"||!body.licenseKey)return null;return{project:{id:String(project.id),name:String(project.name??project.id)},ingestKey:"",readKey:"",licenseKey:body.licenseKey,dashboardUrl:httpUrl(body.dashboardUrl,base)??""}}if(typeof body.ingestKey!=="string"||typeof body.readKey!=="string")return null;if(!body.ingestKey||!body.readKey)return null;return{project:{id:String(project.id),name:String(project.name??project.id)},ingestKey:body.ingestKey,readKey:body.readKey,dashboardUrl:httpUrl(body.dashboardUrl,base)??""}}async function request(deps,url,init={}){const signals=[AbortSignal.timeout(REQUEST_TIMEOUT_MS),...deps.signal?[deps.signal]:[]];try{return await deps.fetch(url,{...init,signal:AbortSignal.any(signals)})}catch{return null}}function retryAfterMs(response,fallback){const seconds=Number(response.headers.get("retry-after"));return Number.isFinite(seconds)&&seconds>0?Math.min(seconds,60)*1000:fallback}export function resolveHqServices(requested,fallback=HQ_DEFAULT_SERVICES){const names=requested.map((name)=>name.trim().toLowerCase()).filter(Boolean);if(!names.length)return{services:[...fallback]};const unknown=names.filter((name)=>!(name in HQ_SERVICES));if(unknown.length)return{error:`Unknown service: ${unknown.join(", ")}. Choose from ${HQ_SERVICE_NAMES.join(", ")}.`};return{services:[...new Set(names)]}}async function connectOne(service,url,options,deps){const{label}=HQ_SERVICES[service];const base=origin(url);const outcome=(status,detail)=>({outcome:{service,status,detail,send:"skipped",read:"skipped"}});const started=await request(deps,`${base}/api/cli/connect`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({app:options.app})});if(deps.signal?.aborted)return outcome("cancelled","cancelled");if(!started)return outcome("unreachable",`could not reach ${base}`);if(started.status===404||started.status===405)return outcome("unavailable","not available yet");if(started.status===429)return outcome("failed","too many requests, try again in a minute");if(!started.ok)return outcome("failed",`the service answered ${started.status}`);const body=await started.json().catch(()=>null);const code=isRecord(body)&&typeof body.code==="string"&&/^[\w-]{16,128}$/.test(body.code)?body.code:null;const approveUrl=isRecord(body)?httpUrl(body.approveUrl,base):null;if(!code||!approveUrl)return outcome("failed","the service answered something that is not a connect code");const confirmCode=isRecord(body)&&typeof body.confirmCode==="string"&&/^[\w-]{1,32}$/.test(body.confirmCode)?body.confirmCode:null;deps.print("");deps.print(`${label}: approve this connection in your browser`);deps.print(` ${approveUrl}`);if(confirmCode)deps.print(` Confirmation code: ${confirmCode} (type it on that page)`);deps.print(" If the page asks you to sign in, sign in and open the link again.");deps.print(" Waiting for approval. Press Ctrl+C to cancel.");if(options.open!==false){try{await deps.open(approveUrl)}catch{}}const interval=options.pollIntervalMs??2000;const deadline=deps.now()+(options.timeoutMs??10*60*1000);const pollUrl=`${base}/api/cli/connect/${encodeURIComponent(code)}`;while(true){if(deps.signal?.aborted)return outcome("cancelled","cancelled");if(deps.now()>=deadline)return outcome("timeout","nobody approved it in time");await deps.sleep(Math.min(interval,Math.max(0,deadline-deps.now())),deps.signal);if(deps.signal?.aborted)return outcome("cancelled","cancelled");const polled=await request(deps,pollUrl,{headers:{Accept:"application/json"}});if(!polled)continue;if(polled.status===429){await deps.sleep(retryAfterMs(polled,interval),deps.signal);continue}if(polled.status===404)return outcome("expired","the request expired, run the command again");if(!polled.ok)return outcome("failed",`the service answered ${polled.status}`);const answer=await polled.json().catch(()=>null);if(!isRecord(answer)||answer.status==="pending")continue;if(answer.status==="expired")return outcome("expired","the request expired, run the command again");const grant=toGrant(answer,base,Boolean(HQ_SERVICES[service].env.license));if(!grant)return outcome("failed","the service approved the request without sending keys");return{grant,outcome:{service,status:"connected",project:grant.project.name,dashboardUrl:grant.dashboardUrl||undefined,send:"skipped",read:"skipped"}}}}function envEntries(service,grant){const names=HQ_SERVICES[service].env;const entries={};if(names.license&&grant.licenseKey)return{[names.license]:grant.licenseKey};if(names.key)entries[names.key]=grant.ingestKey;if(names.readKey)entries[names.readKey]=grant.readKey;if(names.project)entries[names.project]=grant.project.id;return entries}async function verify(service,url,grant,options,deps){const kind=HQ_SERVICES[service].verify;if(!kind)return{send:"skipped",read:"skipped"};const base=origin(url);if(kind==="support"){const client=createHqClient({services:{supporthq:{url:base,readKey:grant.readKey,project:grant.project.id}},fetch:deps.fetch});const result=await client.support.conversations({limit:1});return result.ok?{send:"skipped",read:"pass"}:{send:"skipped",read:"fail",detail:describeUnavailable(result)}}const marker=`hq-connect-${crypto.randomUUID().slice(0,8)}`;const message=`buddy hq:connect test ${marker}`;const timestamp=new Date(deps.now()).toISOString();const sent=kind==="log"?await request(deps,`${base}/logs`,{method:"POST",headers:{"Content-Type":"application/json","X-LogHQ-Key":grant.ingestKey},body:JSON.stringify({logs:[{level:"info",message,timestamp,context:{source:"buddy hq:connect"}}]})}):await request(deps,`${base}/errors`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:grant.ingestKey,type:"HqConnectTest",message,level:"info",environment:"hq-connect",timestamp,sdk:{name:"buddy.hq-connect"}})});if(!sent?.ok)return{send:"fail",read:"skipped",detail:sent?`sending the test ${kind} answered ${sent.status}`:`sending the test ${kind} did not get through`};const receipt=await sent.json().catch(()=>null);if(isRecord(receipt)&&(receipt.sampled===true||receipt.stored===0))return{send:"pass",read:"skipped",detail:`the plan allowance is used up, so the test ${kind} was not kept`};const client=createHqClient({services:{[service]:{url:base,readKey:grant.readKey,project:grant.project.id}},timeoutMs:REQUEST_TIMEOUT_MS,fetch:(input,init)=>deps.fetch(input,init)});let reason=`the test ${kind} was accepted but did not show up`;const attempts=options.readAttempts??5;for(let attempt=0;attempt<attempts;attempt++){if(attempt>0)await deps.sleep(1000,deps.signal);if(deps.signal?.aborted)return{send:"pass",read:"fail",detail:"cancelled"};if(kind==="log"){const page=await client.logs.list({search:marker,limit:5});if(page.ok&&page.data.logs.some((log)=>log.message.includes(marker)))return{send:"pass",read:"pass"};if(!page.ok)reason=describeUnavailable(page)}else{const list=await client.issues.list();if(list.ok&&list.data.some((issue)=>issue.title.includes(marker)))return{send:"pass",read:"pass"};if(!list.ok)reason=describeUnavailable(list)}}return{send:"pass",read:"fail",detail:reason}}export function describeUnavailable(result){switch(result.reason){case"not_configured":return"not connected";case"unauthorized":return"the read key was refused";case"timeout":return"the service did not answer in time";case"network":return"the service could not be reached";case"http":return result.status===404?"not available yet":`the service answered ${result.status}`;case"bad_response":return"the service answered something unexpected"}}export function renderTable(headers,rows){const widths=headers.map((header,column)=>Math.max(header.length,...rows.map((row)=>(row[column]??"").length)));const line=(cells)=>cells.map((cell,column)=>(cell??"").padEnd(widths[column])).join(" ").trimEnd();return[line(headers),line(widths.map((width)=>"-".repeat(width))),...rows.map(line)]}const CONNECT_WORDS={connected:"pass",unavailable:"not available yet",unreachable:"fail",expired:"fail",timeout:"fail",cancelled:"cancelled",failed:"fail"};const CHECK_WORDS={pass:"pass",fail:"fail",skipped:"-"};export function connectTable(outcomes){return renderTable(["Service","Connect","Send","Read back","Note"],outcomes.map((outcome)=>[HQ_SERVICES[outcome.service].label,CONNECT_WORDS[outcome.status],CHECK_WORDS[outcome.send],CHECK_WORDS[outcome.read],outcome.status==="unavailable"?"":outcome.detail??""]))}export async function runHqConnect(services,config,options,deps){const outcomes=[];for(const service of services){const{label}=HQ_SERVICES[service];if(deps.signal?.aborted){outcomes.push({service,status:"cancelled",detail:"cancelled",send:"skipped",read:"skipped"});continue}const url=config[service]?.url;if(!url){outcomes.push({service,status:"failed",detail:"no URL is configured in config/services.ts",send:"skipped",read:"skipped"});continue}const{outcome,grant}=await connectOne(service,url,options,deps);if(!grant){if(outcome.status==="unavailable")deps.print(`${label}: not available yet`);else if(outcome.status!=="cancelled")deps.print(`${label}: not connected (${outcome.detail})`);outcomes.push(outcome);continue}try{await deps.writeEnv(envEntries(service,grant))}catch(error){const why=error instanceof Error?error.message:"unknown error";deps.print(`${label}: approved, but the keys could not be written to .env (${why})`);outcomes.push({...outcome,status:"failed",detail:"the keys could not be written to .env"});continue}deps.print(grant.licenseKey?`${label}: licensed "${grant.project.name}". Licence written to .env.`:`${label}: connected to project "${grant.project.name}". Keys written to .env.`);if(grant.dashboardUrl)deps.print(` Dashboard: ${grant.dashboardUrl}`);if(options.verify===false){outcomes.push(outcome);continue}outcomes.push({...outcome,...await verify(service,url,grant,options,deps)})}if(deps.signal?.aborted)deps.print("Cancelled. Services already connected keep their keys.");deps.print("");for(const line of connectTable(outcomes))deps.print(line);const ok=outcomes.every((outcome)=>outcome.status==="unavailable"||outcome.status==="connected"&&outcome.send!=="fail"&&outcome.read!=="fail");return{outcomes,ok}}const count=(value)=>value.toLocaleString("en-US");const REPORTSHQ_LICENSE=/^rhq_lic_[0-9a-f]{32}$/;export function describeReportsHqLicense(license){if(!license)return"unlicensed. Reports work in full; set REPORTSHQ_LICENSE to remove the notice";return REPORTSHQ_LICENSE.test(license)?"licensed (checked offline, nothing is metered)":"the licence key is not in the expected format. Reports are unaffected"}export async function runHqStatus(config,deps,services=HQ_SERVICE_NAMES){const connected=services.filter((service)=>config[service]?.url&&config[service]?.readKey);const license=services.includes("reportshq")?config.reportshq?.license:undefined;if(!connected.length&&!license){deps.print("No HQ service is connected yet. Run `buddy hq:connect` to connect one.");return[]}const client=createHqClient({services:Object.fromEntries(connected.map((service)=>[service,{url:config[service].url,readKey:config[service].readKey}])),timeoutMs:REQUEST_TIMEOUT_MS,fetch:(input,init)=>deps.fetch(input,init)});const rows=[];for(const[index,usage]of(await Promise.all(connected.map((service)=>client.getUsage(service)))).entries()){const service=connected[index];if(!usage.ok){rows.push({service,unavailable:describeUnavailable(usage)});continue}if(!usage.data.length)rows.push({service,unavailable:"no meters reported"});for(const report of usage.data){const over=report.limit!==null&&report.limit>0&&report.used/report.limit>=0.8;rows.push({service,meter:report.meter,used:report.used,limit:report.limit,period:report.period,state:report.state,...over?{upgradeUrl:report.upgradeUrl}:{}})}}if(license)rows.push({service:"reportshq",unavailable:describeReportsHqLicense(license)});const table=renderTable(["Service","Meter","Used","Limit","Period","State"],rows.map((row)=>row.unavailable?[HQ_SERVICES[row.service].label,row.unavailable]:[HQ_SERVICES[row.service].label,row.meter,count(row.used),row.limit===null?"unlimited":count(row.limit),row.period,row.state]));for(const line of table)deps.print(line);const upgrades=rows.filter((row)=>row.upgradeUrl);if(upgrades.length)deps.print("");for(const row of upgrades){const percent=Math.round(row.used/row.limit*100);deps.print(`${HQ_SERVICES[row.service].label} ${row.meter} is at ${percent}% of its allowance. Upgrade: ${row.upgradeUrl}`)}return rows}export async function runSupportDoctor(config,deps,options={}){const service=config.supporthq;const configured=Boolean(service?.url&&service.key&&service.readKey&&service.project);const checks=[{name:"configuration",ok:configured,detail:configured?"server key, read key and project configured":"missing configuration; run `buddy support:install`"}];if(configured){const client=createHqClient({services:{supporthq:{url:service.url,readKey:service.readKey,project:service.project}},fetch:deps.fetch});const usage=await client.getUsage("supporthq");checks.push({name:"usage",ok:usage.ok,detail:usage.ok?`${usage.data.length} usage meters readable`:describeUnavailable(usage)});const conversations=await client.support.conversations({limit:1});checks.push({name:"conversations",ok:conversations.ok,detail:conversations.ok?"project summaries readable":describeUnavailable(conversations)});if(service?.enabled===true){try{const target=new URL(service.url);if(target.username||target.password||target.search||target.hash||target.pathname!=="/"||target.protocol!=="https:"&&!(target.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(target.hostname)))throw new Error("Invalid support origin");const base=target.origin;const probe=await deps.fetch(`${base}/api/v1/projects/${encodeURIComponent(service.project)}/installation`,{headers:{Authorization:`Bearer ${service.key}`},redirect:"error",signal:AbortSignal.timeout(1e4)});const body=probe.ok?await probe.json():null;const current=new URL(options.origin||"").origin;const accepted=isRecord(body)&&body.service==="supporthq"&&body.protocol===1&&body.project===service.project&&body.buddyConnected===true&&Array.isArray(body.allowedOrigins)&&body.allowedOrigins.includes(current);checks.push({name:"installation",ok:accepted,detail:accepted?"approved project and exact app origin; no customer probe was created":"native installation or app origin is not approved"})}catch{checks.push({name:"installation",ok:false,detail:"native installation could not be read"})}if(service.messenger?.enabled){try{const loader=new URL(service.messenger.loaderUrl||"https://hq.support/support.js");if(loader.username||loader.password||loader.search||loader.hash||loader.protocol!=="https:"&&!(loader.protocol==="http:"&&["localhost","127.0.0.1","[::1]"].includes(loader.hostname)))throw new Error("Invalid loader");const response=await deps.fetch(new URL("/widgets/manifest.json",loader).href,{redirect:"error",signal:AbortSignal.timeout(1e4)});const manifest=response.ok?await response.json():null;const published=isRecord(manifest)&&manifest.schemaVersion===1&&Array.isArray(manifest.files)&&manifest.files.some((file)=>isRecord(file)&&typeof file.path==="string"&&file.path.endsWith("/bundle.js")&&typeof file.sha256==="string"&&/^[a-f0-9]{64}$/.test(file.sha256)&&typeof file.gzipBytes==="number"&&file.gzipBytes>0&&file.gzipBytes<=1e5);checks.push({name:"widget",ok:published,detail:published?"published manifest reports a versioned widget within the initial code budget":"published widget manifest or size budget is unavailable"})}catch{checks.push({name:"widget",ok:false,detail:"published widget could not be checked"})}}}}for(const check of checks)deps.print(`HQ.support ${check.name}: ${check.ok?"pass":"fail"} (${check.detail})`);return{ok:checks.every((check)=>check.ok),checks}}
@@ -1 +1 @@
1
- import{FEATURE_NAMES}from"@stacksjs/features";const APP_KEY_OPTIONAL_COMMANDS=["env","desktop:apple","build","workflow","link:core","unlink:core","lint","docs","release","lint:fix","test","test:types","test:unit","test:feature","typecheck","types:fix","types:generate","clean","fresh","about","ai:context","doctor","list","setup","setup:ssl","setup:oh-my-zsh","deploy","serve","new","create","upgrade","update","migrate","seed","generate","make","key:generate","scaffold:crud"];export function shouldSkipAppKeyCheck(requestedCommand,mode={}){return Boolean(mode.isHelpFlag||mode.isHelpMode||FEATURE_NAMES.some((feature)=>requestedCommand===`${feature}:install`||requestedCommand===`${feature}:uninstall`)||APP_KEY_OPTIONAL_COMMANDS.some((command)=>requestedCommand===command||requestedCommand.startsWith(`${command}:`)))}
1
+ import{FEATURE_NAMES}from"@stacksjs/features";const APP_KEY_OPTIONAL_COMMANDS=["env","desktop:apple","build","workflow","link:core","unlink:core","publish:core","unpublish:core","publish:defaults","unpublish:defaults","lint","docs","release","lint:fix","test","test:types","test:unit","test:feature","typecheck","types:fix","types:generate","clean","fresh","about","ai:context","doctor","list","setup","setup:ssl","setup:oh-my-zsh","deploy","serve","new","create","upgrade","update","migrate","seed","generate","make","key:generate","scaffold:crud"];export function shouldSkipAppKeyCheck(requestedCommand,mode={}){return Boolean(mode.isHelpFlag||mode.isHelpMode||FEATURE_NAMES.some((feature)=>requestedCommand===`${feature}:install`||requestedCommand===`${feature}:uninstall`)||APP_KEY_OPTIONAL_COMMANDS.some((command)=>requestedCommand===command||requestedCommand.startsWith(`${command}:`)))}
@@ -1,4 +1,4 @@
1
- function relativePath(value){return typeof value==="string"&&!!value&&!/^[A-Za-z]:|^[\\/]|[\\\r\n\x00]/.test(value)&&!value.split("/").some((segment)=>segment==="."||segment==="..")}export function validateWorkflowConfig(config){const origin=new URL(config.origin);if(config.provider!=="reviewos"||origin.protocol!=="https:"||origin.username||origin.password||origin.pathname!=="/"||origin.search||origin.hash||!/^[\w.-]+\/[\w.-]+$/.test(config.repository)||config.repository.split("/").some((part)=>part==="."||part===".."))throw new Error("Configure a canonical ReviewOS origin and owner/repository");for(const group of["checks",...config.deploy?["deploy"]:[],...config.native?["ios"]:[]]){const labels=config.runners[group];if(!Array.isArray(labels)||!labels.includes("self-hosted")||labels.some((label)=>!/^[\w.-]+$/.test(label)))throw new Error(`Declare the owned ${group} runner labels`)}for(const values of Object.values(config.env??{})){if(!values||typeof values!=="object"||Array.isArray(values)||Object.entries(values).some(([name,value])=>!/^[A-Z_][A-Z0-9_]*$/.test(name)||typeof value!=="string"||value.includes("\x00")))throw new Error("Workflow environment settings must be named string values")}for(const names of Object.values(config.secrets??{})){if(!Array.isArray(names)||names.some((name)=>!/^[A-Z_][A-Z0-9_]*$/.test(name)))throw new Error("Workflow secrets must be environment variable names")}for(const[step,names]of Object.entries(config.stepSecrets??{})){if(!["native-build","native-accept","native-sign","native-upload","native-verify","native-cleanup"].includes(step)||!Array.isArray(names)||names.some((name)=>!config.secrets?.ios?.includes(name)))throw new Error("Step credentials must name declared native secrets")}if(config.native&&(!config.native.artifacts.length||![...config.native.artifacts,config.native.downloadDirectory,config.native.archivePattern,...config.native.evidence??[],...config.native.releaseArtifacts??[]].every(relativePath)))throw new Error("Native artifacts must stay inside the workspace");if(config.deploy&&!config.commands?.["after-deploy"]?.length)throw new Error("Configure deployed application verification");if(config.native&&["native-build","native-accept"].some((step)=>!config.commands?.[step]?.length))throw new Error("Configure native build and downloaded acceptance commands");if(config.release&&(!config.native||["native-sign","native-upload","native-verify","native-cleanup"].some((step)=>!config.commands?.[step]?.length)))throw new Error("Configure native signing, upload, verification and cleanup before releasing");if(config.release&&(!relativePath(config.release.versionFile)||config.release.notesDirectory!==undefined&&!relativePath(config.release.notesDirectory)||config.release.locales?.some((locale)=>!/^[a-z]{2}(?:-[A-Z]{2})?$/.test(locale))))throw new Error("Release files and locales must stay inside the workspace");for(const commands of Object.values(config.commands??{})){if(!Array.isArray(commands)||commands.some((argv)=>!Array.isArray(argv)||!argv.length||argv.some((arg)=>typeof arg!=="string"||arg.includes("\x00"))))throw new Error("Workflow commands must be nonempty argv arrays")}}export function renderReviewOsWorkflow(config){validateWorkflowConfig(config);const branch=config.branch??"main";if(!/^[\w./-]+$/.test(branch)||branch.includes(".."))throw new Error("Configure a branch name");const main=`github.ref == 'refs/heads/${branch}' && github.event_name != 'pull_request'`;const upload="steps.release.outputs.upload == 'true'";const secretEnv=(group)=>Object.fromEntries((config.secrets?.[group]??[]).map((name)=>[name,"${{ secrets."+name+" }}"]));const nativeSecrets=(step)=>{const names=config.stepSecrets?.[step]??(step==="native-sign"?config.secrets?.ios??[]:[]);return names.length?{env:Object.fromEntries(names.map((name)=>[name,"${{ secrets."+name+" }}"]))}:{}};const bootstrap=()=>[{name:"Checkout the exact source",uses:"actions/checkout@11d5960a326750d5838078e36cf38b85af677262",with:{"fetch-depth":0,"persist-credentials":false}},{name:"Set up the pinned tools",uses:"pantry-pm/pantry/packages/action@624cd6674f8c5c2d4e4204c11ece62a00d7fac0a",with:{version:config.pantry??"0.11.199",install:"false",packages:`bun.sh@${config.bun??"1.4.4"}`}},{name:"Install the frozen application dependencies",run:"bun install --frozen-lockfile"},{name:"Prepare declared application inputs",run:"./buddy workflow:step prepare"}];const jobs={};for(const name of["lint","typecheck","test","build"])jobs[name]={"runs-on":config.runners.checks,"timeout-minutes":name==="test"?90:30,reviewos:{secrets:config.secrets?.checks??[]},env:{...config.env?.checks,...secretEnv("checks")},steps:[...bootstrap(),{name:`Run ${name}`,run:`./buddy workflow:step ${name}`}]};if(config.deploy)jobs.deploy={needs:["lint","typecheck","test","build"],if:main,"runs-on":config.runners.deploy,"timeout-minutes":60,environment:"production",reviewos:{secrets:[...config.secrets?.checks??[],...config.secrets?.deploy??[]]},env:{...config.env?.checks,...config.env?.deploy,...secretEnv("checks"),...secretEnv("deploy")},steps:[...bootstrap(),{name:"Deploy the qualified source",run:"./buddy workflow:step deploy"},{name:"Verify the deployed application",run:"./buddy workflow:step after-deploy"}]};if(config.native)jobs.native={needs:config.deploy?["deploy"]:["lint","typecheck","test","build"],if:main,"runs-on":config.runners.ios,"timeout-minutes":90,environment:"ios-testflight",reviewos:{secrets:[...config.secrets?.checks??[],...config.secrets?.ios??[]]},env:{...config.env?.checks,...config.env?.ios,...secretEnv("checks")},steps:[...bootstrap(),{name:"Read the committed release identity",id:"release",run:"./buddy workflow:release-state",env:{WORKFLOW_UPLOAD_REQUESTED:"${{ inputs.upload && 'true' || 'false' }}"}},{name:"Build the simulator application",run:"./buddy workflow:step native-build",...nativeSecrets("native-build")},{name:"Publish the simulator application",uses:"actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02",with:{name:"native-simulator-${{ github.run_id }}",path:config.native.artifacts.join(`
2
- `),"if-no-files-found":"error","retention-days":7}},{name:"Download the published application",uses:"actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093",with:{name:"native-simulator-${{ github.run_id }}",path:config.native.downloadDirectory}},{name:"Accept the downloaded application",run:"./buddy workflow:step native-accept",...nativeSecrets("native-accept")},{name:"Prepare temporary signing material",if:upload,run:"./buddy workflow:step native-sign",...nativeSecrets("native-sign")},{name:"Upload the accepted application",if:upload,run:"./buddy workflow:step native-upload",...nativeSecrets("native-upload")},{name:"Verify tester availability",if:upload,run:"./buddy workflow:step native-verify",...nativeSecrets("native-verify")},{name:"Remove temporary signing material",if:"always()",run:"./buddy workflow:step native-cleanup",...nativeSecrets("native-cleanup")},...[...config.native.evidence??[],...config.native.releaseArtifacts??[]].length?[{name:"Preserve acceptance and release receipts",if:"always()",uses:"actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02",with:{name:"native-evidence-${{ github.run_id }}",path:[...config.native.evidence??[],...config.native.releaseArtifacts??[]].join(`
1
+ function relativePath(value){return typeof value==="string"&&!!value&&!/^[A-Za-z]:|^[\\/]|[\\\r\n\x00]/.test(value)&&!value.split("/").some((segment)=>segment==="."||segment==="..")}export function validateWorkflowConfig(config){const origin=new URL(config.origin);if(config.provider!=="reviewos"||origin.protocol!=="https:"||origin.username||origin.password||origin.pathname!=="/"||origin.search||origin.hash||!/^[\w.-]+\/[\w.-]+$/.test(config.repository)||config.repository.split("/").some((part)=>part==="."||part===".."))throw new Error("Configure a canonical ReviewOS origin and owner/repository");for(const group of["checks",...config.deploy?["deploy"]:[],...config.native?["ios"]:[]]){const labels=config.runners[group];if(!Array.isArray(labels)||!labels.includes("self-hosted")||labels.some((label)=>!/^[\w.-]+$/.test(label)))throw new Error(`Declare the owned ${group} runner labels`)}for(const values of Object.values(config.env??{})){if(!values||typeof values!=="object"||Array.isArray(values)||Object.entries(values).some(([name,value])=>!/^[A-Z_][A-Z0-9_]*$/.test(name)||typeof value!=="string"||value.includes("\x00")))throw new Error("Workflow environment settings must be named string values")}for(const names of Object.values(config.secrets??{})){if(!Array.isArray(names)||names.some((name)=>!/^[A-Z_][A-Z0-9_]*$/.test(name)))throw new Error("Workflow secrets must be environment variable names")}for(const[step,names]of Object.entries(config.stepSecrets??{})){if(!["native-build","native-accept","native-sign","native-upload","native-verify","native-cleanup"].includes(step)||!Array.isArray(names)||names.some((name)=>!config.secrets?.ios?.includes(name)))throw new Error("Step credentials must name declared native secrets")}if(config.native&&(!config.native.artifacts.length||![...config.native.artifacts,config.native.downloadDirectory,config.native.archivePattern,...config.native.evidence??[],...config.native.releaseArtifacts??[]].every(relativePath)))throw new Error("Native artifacts must stay inside the workspace");if(config.deploy&&!config.commands?.["after-deploy"]?.length)throw new Error("Configure deployed application verification");if(config.native&&["native-build","native-accept"].some((step)=>!config.commands?.[step]?.length))throw new Error("Configure native build and downloaded acceptance commands");if(config.release&&(!config.native||["native-sign","native-upload","native-verify","native-cleanup"].some((step)=>!config.commands?.[step]?.length)))throw new Error("Configure native signing, upload, verification and cleanup before releasing");if(config.release&&(!relativePath(config.release.versionFile)||config.release.notesDirectory!==undefined&&!relativePath(config.release.notesDirectory)||config.release.locales?.some((locale)=>!/^[a-z]{2}(?:-[A-Z]{2})?$/.test(locale))))throw new Error("Release files and locales must stay inside the workspace");for(const commands of Object.values(config.commands??{})){if(!Array.isArray(commands)||commands.some((argv)=>!Array.isArray(argv)||!argv.length||argv.some((arg)=>typeof arg!=="string"||arg.includes("\x00"))))throw new Error("Workflow commands must be nonempty argv arrays")}}export function renderReviewOsWorkflow(config){validateWorkflowConfig(config);const branch=config.branch??"main";if(!/^[\w./-]+$/.test(branch)||branch.includes(".."))throw new Error("Configure a branch name");const main=`github.ref == 'refs/heads/${branch}' && github.event_name != 'pull_request'`;const upload="steps.release.outputs.upload == 'true'";const secretEnv=(group)=>Object.fromEntries((config.secrets?.[group]??[]).map((name)=>[name,"${{ secrets."+name+" }}"]));const nativeSecrets=(step)=>{const names=config.stepSecrets?.[step]??(step==="native-sign"?config.secrets?.ios??[]:[]);return names.length?{env:Object.fromEntries(names.map((name)=>[name,"${{ secrets."+name+" }}"]))}:{}};const bootstrap=()=>[{name:"Checkout the exact source",uses:"actions/checkout@11d5960a326750d5838078e36cf38b85af677262",with:{"fetch-depth":0,"persist-credentials":false}},{name:"Set up the pinned tools",uses:"pantry-pm/pantry/packages/action@624cd6674f8c5c2d4e4204c11ece62a00d7fac0a",with:{version:config.pantry??"0.11.199",install:"false",packages:`bun.sh@${config.bun??"1.4.4"}`}},{name:"Install the frozen application dependencies",run:"bun install --frozen-lockfile"},{name:"Prepare declared application inputs",run:"./buddy workflow:step prepare"}];const jobs={};for(const name of["lint","typecheck","test","build"])jobs[name]={"runs-on":config.runners.checks,"timeout-minutes":name==="test"?90:30,reviewos:{secrets:config.secrets?.checks??[]},env:{...config.env?.checks,...secretEnv("checks")},steps:[...bootstrap(),{name:`Run ${name}`,run:`./buddy workflow:step ${name}`}]};if(config.deploy)jobs.deploy={needs:["lint","typecheck","test","build"],if:main,"runs-on":config.runners.deploy,"timeout-minutes":60,environment:"production",reviewos:{secrets:[...config.secrets?.checks??[],...config.secrets?.deploy??[]]},env:{...config.env?.checks,...config.env?.deploy,...secretEnv("checks"),...secretEnv("deploy")},steps:[...bootstrap(),{name:"Deploy the qualified source",run:"./buddy workflow:step deploy"},{name:"Verify the deployed application",run:"./buddy workflow:step after-deploy"}]};if(config.native)jobs.native={needs:config.deploy?["deploy"]:["lint","typecheck","test","build"],if:main,"runs-on":config.runners.ios,"timeout-minutes":90,environment:"ios-testflight",reviewos:{secrets:[...config.secrets?.checks??[],...config.secrets?.ios??[]]},env:{...config.env?.checks,...config.env?.ios,...secretEnv("checks")},steps:[...bootstrap(),{name:"Read the committed release identity",id:"release",run:"./buddy workflow:release-state",env:{WORKFLOW_UPLOAD_REQUESTED:"${{ inputs.upload && 'true' || 'false' }}"}},{name:"Build the simulator application",run:"./buddy workflow:step native-build",...nativeSecrets("native-build")},{name:"Publish the simulator application",uses:"actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02",with:{name:"native-simulator-${{ github.run_id }}-${{ github.run_attempt }}",path:config.native.artifacts.join(`
2
+ `),"if-no-files-found":"error","retention-days":7}},{name:"Download the published application",uses:"actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093",with:{name:"native-simulator-${{ github.run_id }}-${{ github.run_attempt }}",path:config.native.downloadDirectory}},{name:"Accept the downloaded application",run:"./buddy workflow:step native-accept",...nativeSecrets("native-accept")},{name:"Prepare temporary signing material",if:upload,run:"./buddy workflow:step native-sign",...nativeSecrets("native-sign")},{name:"Upload the accepted application",if:upload,run:"./buddy workflow:step native-upload",...nativeSecrets("native-upload")},{name:"Verify tester availability",if:upload,run:"./buddy workflow:step native-verify",...nativeSecrets("native-verify")},{name:"Remove temporary signing material",if:"always()",run:"./buddy workflow:step native-cleanup",...nativeSecrets("native-cleanup")},...[...config.native.evidence??[],...config.native.releaseArtifacts??[]].length?[{name:"Preserve acceptance and release receipts",if:"always()",uses:"actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02",with:{name:"native-evidence-${{ github.run_id }}-${{ github.run_attempt }}",path:[...config.native.evidence??[],...config.native.releaseArtifacts??[]].join(`
3
3
  `),"if-no-files-found":"warn","retention-days":7}}]:[]]};return`# Generated by buddy workflow:setup from config/workflows.ts.
4
- `+Bun.YAML.stringify({name:"CI",on:{push:{branches:[branch]},pull_request:{branches:[branch]},workflow_dispatch:{inputs:{upload:{type:"boolean",default:false,description:"Upload a committed release after native acceptance"}}}},concurrency:{group:"stacks-app-${{ github.ref }}","cancel-in-progress":`\${{ github.ref != 'refs/heads/${branch}' }}`},permissions:{contents:"read"},jobs})}
4
+ `+Bun.YAML.stringify({name:"CI",on:{push:{branches:[branch]},pull_request:{branches:[branch]},workflow_dispatch:{inputs:{upload:{type:"boolean",default:false,description:"Upload a committed release after native acceptance"}}}},concurrency:{group:"stacks-app-${{ github.ref }}","cancel-in-progress":`\${{ github.ref != 'refs/heads/${branch}' }}`},permissions:{contents:"read"},jobs},null,2)}
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.602",
5
+ "version": "0.75.606",
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.602",
99
- "@stacksjs/docs": "0.75.602",
100
- "@stacksjs/ai": "0.75.602",
101
- "@stacksjs/alias": "0.75.602",
102
- "@stacksjs/analytics": "0.75.602",
103
- "@stacksjs/api": "0.75.602",
104
- "@stacksjs/arrays": "0.75.602",
105
- "@stacksjs/auth": "0.75.602",
106
- "@stacksjs/browser-extension": "0.75.602",
107
- "@stacksjs/build": "0.75.602",
98
+ "@stacksjs/actions": "0.75.606",
99
+ "@stacksjs/docs": "0.75.606",
100
+ "@stacksjs/ai": "0.75.606",
101
+ "@stacksjs/alias": "0.75.606",
102
+ "@stacksjs/analytics": "0.75.606",
103
+ "@stacksjs/api": "0.75.606",
104
+ "@stacksjs/arrays": "0.75.606",
105
+ "@stacksjs/auth": "0.75.606",
106
+ "@stacksjs/browser-extension": "0.75.606",
107
+ "@stacksjs/build": "0.75.606",
108
108
  "@stacksjs/bumpx": "^0.2.32",
109
- "@stacksjs/cache": "0.75.602",
110
- "@stacksjs/chat": "0.75.602",
109
+ "@stacksjs/cache": "0.75.606",
110
+ "@stacksjs/chat": "0.75.606",
111
111
  "@stacksjs/clapp": "^0.2.17",
112
- "@stacksjs/cli": "0.75.602",
113
- "@stacksjs/cloud": "0.75.602",
114
- "@stacksjs/cms": "0.75.602",
115
- "@stacksjs/collections": "0.75.602",
116
- "@stacksjs/commerce": "0.75.602",
117
- "@stacksjs/config": "0.75.602",
118
- "@stacksjs/database": "0.75.602",
119
- "@stacksjs/desktop-build": "0.75.602",
120
- "@stacksjs/dns": "0.75.602",
112
+ "@stacksjs/cli": "0.75.606",
113
+ "@stacksjs/cloud": "0.75.606",
114
+ "@stacksjs/cms": "0.75.606",
115
+ "@stacksjs/collections": "0.75.606",
116
+ "@stacksjs/commerce": "0.75.606",
117
+ "@stacksjs/config": "0.75.606",
118
+ "@stacksjs/database": "0.75.606",
119
+ "@stacksjs/desktop-build": "0.75.606",
120
+ "@stacksjs/dns": "0.75.606",
121
121
  "@stacksjs/dnsx": "^0.2.3",
122
- "@stacksjs/email": "0.75.602",
123
- "@stacksjs/enums": "0.75.602",
124
- "@stacksjs/env": "0.75.602",
125
- "@stacksjs/error-handling": "0.75.602",
126
- "@stacksjs/events": "0.75.602",
127
- "@stacksjs/features": "0.75.602",
128
- "@stacksjs/git": "0.75.602",
122
+ "@stacksjs/email": "0.75.606",
123
+ "@stacksjs/enums": "0.75.606",
124
+ "@stacksjs/env": "0.75.606",
125
+ "@stacksjs/error-handling": "0.75.606",
126
+ "@stacksjs/events": "0.75.606",
127
+ "@stacksjs/features": "0.75.606",
128
+ "@stacksjs/git": "0.75.606",
129
129
  "@stacksjs/gitit": "^0.2.5",
130
- "@stacksjs/health": "0.75.602",
131
- "@stacksjs/hq": "0.75.602",
130
+ "@stacksjs/health": "0.75.606",
131
+ "@stacksjs/hq": "0.75.606",
132
132
  "@stacksjs/httx": "^0.1.10",
133
- "@stacksjs/image": "0.75.602",
134
- "@stacksjs/lint": "0.75.602",
135
- "@stacksjs/logging": "0.75.602",
136
- "@stacksjs/notifications": "0.75.602",
137
- "@stacksjs/objects": "0.75.602",
138
- "@stacksjs/orm": "0.75.602",
139
- "@stacksjs/path": "0.75.602",
140
- "@stacksjs/payments": "0.75.602",
141
- "@stacksjs/realtime": "0.75.602",
142
- "@stacksjs/router": "0.75.602",
133
+ "@stacksjs/image": "0.75.606",
134
+ "@stacksjs/lint": "0.75.606",
135
+ "@stacksjs/logging": "0.75.606",
136
+ "@stacksjs/notifications": "0.75.606",
137
+ "@stacksjs/objects": "0.75.606",
138
+ "@stacksjs/orm": "0.75.606",
139
+ "@stacksjs/path": "0.75.606",
140
+ "@stacksjs/payments": "0.75.606",
141
+ "@stacksjs/realtime": "0.75.606",
142
+ "@stacksjs/router": "0.75.606",
143
143
  "@stacksjs/rpx": "^0.11.54",
144
- "@stacksjs/scheduler": "0.75.602",
145
- "@stacksjs/search-engine": "0.75.602",
146
- "@stacksjs/security": "0.75.602",
147
- "@stacksjs/server": "0.75.602",
148
- "@stacksjs/sites": "0.75.602",
149
- "@stacksjs/skills": "0.75.602",
150
- "@stacksjs/socials": "0.75.602",
151
- "@stacksjs/storage": "0.75.602",
152
- "@stacksjs/strings": "0.75.602",
144
+ "@stacksjs/scheduler": "0.75.606",
145
+ "@stacksjs/search-engine": "0.75.606",
146
+ "@stacksjs/security": "0.75.606",
147
+ "@stacksjs/server": "0.75.606",
148
+ "@stacksjs/sites": "0.75.606",
149
+ "@stacksjs/skills": "0.75.606",
150
+ "@stacksjs/socials": "0.75.606",
151
+ "@stacksjs/storage": "0.75.606",
152
+ "@stacksjs/strings": "0.75.606",
153
153
  "@stacksjs/stx": "^0.2.889",
154
- "@stacksjs/testing": "0.75.602",
155
- "@stacksjs/tinker": "0.75.602",
154
+ "@stacksjs/testing": "0.75.606",
155
+ "@stacksjs/tinker": "0.75.606",
156
156
  "@stacksjs/tlsx": "^0.13.19",
157
- "@stacksjs/ts-cloud": "^0.16.135",
158
- "@stacksjs/tunnel": "0.75.602",
159
- "@stacksjs/types": "0.75.602",
160
- "@stacksjs/ui": "0.75.602",
161
- "@stacksjs/utils": "0.75.602",
162
- "@stacksjs/validation": "0.75.602",
157
+ "@stacksjs/ts-cloud": "^0.16.136",
158
+ "@stacksjs/tunnel": "0.75.606",
159
+ "@stacksjs/types": "0.75.606",
160
+ "@stacksjs/ui": "0.75.606",
161
+ "@stacksjs/utils": "0.75.606",
162
+ "@stacksjs/validation": "0.75.606",
163
163
  "ajv": "^8.20.0",
164
164
  "ajv-formats": "^3.0.1",
165
165
  "bun-plugin-stx": "^0.2.889",