@medplum/cli 5.0.2 → 5.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +2 -2
- package/dist/esm/index.mjs +1 -1
- package/dist/esm/index.mjs.map +2 -2
- package/package.json +5 -5
package/dist/esm/index.mjs
CHANGED
|
@@ -4,7 +4,7 @@ ${S.length} successful response(s):
|
|
|
4
4
|
`),console.table(S.length?S:"No successful responses received"),console.info(),f.length&&(console.info(`${f.length} failed response(s):`),console.info(),console.table(f))}async function no(e,t,r){if(!(t||r.criteria))throw new Error("This command requires either an [agentId] or a --criteria <criteria> flag");if(t&&r.criteria)throw new Error("Ambiguous arguments and options combination; [agentId] arg and --criteria <criteria> flag are mutually exclusive");let o;if(t)o=t;else{so(r.criteria);let n=await e.search("Agent",`${r.criteria.split("?")[1]}&_count=2`);if(!n?.entry?.length)throw new Error("Could not find an agent matching the provided criteria");if(n.entry.length!==1)throw new Error("Found more than one agent matching this criteria. This operation requires the criteria to resolve to exactly one agent");o=n.entry[0].resource?.id}return{reference:`Agent/${o}`}}function _i(e){let t=[];for(let r of e.entry??[]){if(!r.resource)throw new Error("No Parameter resource found in entry");t.push(Ui(r.resource))}return t}function Ui(e){let t=e.parameter?.find(o=>o.name==="agent")?.resource;if(!t)throw new Error("Agent bulk operation response missing 'agent'");if(t.resourceType!=="Agent")throw new Error(`Agent bulk operation returned 'agent' with type '${t.resourceType}'`);let r=e.parameter?.find(o=>o.name==="result")?.resource;if(!r)throw new Error("Agent bulk operation response missing result'");if(!(r.resourceType==="Parameters"||r.resourceType==="OperationOutcome"))throw new Error(`Agent bulk operation returned 'result' with type '${r.resourceType}'`);return{agent:t,result:r}}function ji(e,t){let r={},o=t.required,n=t.optional;for(let s of o){let i=e.parameter?.find(l=>l.name===s);if(!i)throw new Error(`Failed to find parameter '${s}'`);let a;for(let l in i)if(l.startsWith("value")){if(a)throw new Error(`Found multiple values for parameter '${s}'`);a=l}if(!a)throw new Error(`Failed to find a value for parameter '${s}'`);r[s]=i[a]}if(n?.length)for(let s of n){let i=e.parameter?.find(l=>l.name===s);if(!i)continue;let a=Fi(s,i);r[s]=a}return r}function Fi(e,t){let r;for(let o in t)if(o.startsWith("value")){if(r)throw new Error(`Found multiple values for parameter '${e}'`);r=o}if(!r)throw new Error(`Failed to find a value for parameter '${e}'`);return t[r]}function Bi(e,t){if(!Array.isArray(e))throw new Error("Invalid agent IDs array");if(e.length){if(t.criteria)throw new Error("Ambiguous arguments and options combination; [agentIds...] arg and --criteria <criteria> flag are mutually exclusive");for(let r of e)if(!Mi(r))throw new Error(`Input '${r}' is not a valid agentId`);return{type:"ids",ids:e}}if(t.criteria)return so(t.criteria),{type:"criteria",criteria:t.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function so(e){let t="Criteria must be formatted as a string containing the resource type (Agent) followed by a '?' and valid URL search query params, eg. `Agent?name=Test Agent`";if(typeof e!="string")throw new Error(t);let[r,o]=e.split("?");if(r!=="Agent"||!o)throw new Error(t);try{new URLSearchParams(o)}catch(n){throw new Error(t,{cause:n})}if(!o.includes("="))throw new Error(t,{cause:new Error("Query string lacks at least one `=`")})}import{ContentType as je,getDisplayString as Wi,MEDPLUM_CLI_CLIENT_ID as Ki,normalizeErrorString as qi}from"@medplum/core";import{exec as Hi}from"node:child_process";import{createServer as Gi}from"node:http";import{platform as Vi}from"node:os";var io=Ki,ao="http://localhost:9615",kt=new g("login"),Dt=new g("whoami"),Mt=new g("token");kt.action(async e=>{let t=e.profile??"default",r=Ue(t,e),o=await R(e,!1);await Ji(o,r)});Dt.action(async e=>{let t=await R(e);Yi(t)});Mt.action(async e=>{let t=await R(e);await t.getProfileAsync();let r=t.getAccessToken();if(!r)throw new Error("Not logged in");console.log(r)});async function Ji(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Qi(e);break;case"basic":e.setBasicAuth(t.clientId,t.clientSecret);break;case"client-credentials":e.setBasicAuth(t.clientId,t.clientSecret),await e.startClientLogin(t.clientId,t.clientSecret);break;case"jwt-bearer":await zr(e,t);break;case"jwt-assertion":await Yr(e,t);break}}async function Xi(e){let t=Gi(async(r,o)=>{let n=new URL(r.url,"http://localhost:9615"),s=n.searchParams.get("code");if(r.method==="OPTIONS"){o.writeHead(200,{Allow:"GET, POST","Content-Type":je.TEXT}),o.end("OK");return}if(n.pathname==="/"&&s)try{let i=await e.processCode(s,{clientId:io,redirectUri:ao});o.writeHead(200,{"Content-Type":je.TEXT}),o.end(`Signed in as ${Wi(i)}. You may close this window.`)}catch(i){o.writeHead(400,{"Content-Type":je.TEXT}),o.end(`Error: ${qi(i)}`)}finally{t.close(),process.exit(0)}else o.writeHead(404,{"Content-Type":je.TEXT}),o.end("Not found")}).listen(9615)}async function zi(e){let t=Vi(),r;switch(t){case"openbsd":case"linux":r=`xdg-open '${e}'`;break;case"darwin":r=`open '${e}'`;break;case"win32":r=`cmd /c start "" "${e}"`;break;default:throw new Error("Unsupported platform: "+t)}return new Promise((o,n)=>{Hi(r,(s,i,a)=>{if(s){n(s);return}if(a){n(new Error("Could not open browser: "+a));return}o()})})}function Yi(e){let t=e.getActiveLogin();t?(console.log(`Server: ${e.getBaseUrl()}`),console.log(`Profile: ${t.profile.display} (${t.profile.reference})`),console.log(`Project: ${t.project.display} (${t.project.reference})`)):console.log("Not logged in")}async function Qi(e){await Xi(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",io),t.searchParams.set("redirect_uri",ao),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await zi(t.toString())}var ye="\x1B[0m",Zi="\x1B[1m",ea="\x1B[31m",ta="\x1B[32m",ra="\x1B[33m",oa="\x1B[34m",ee={red:e=>`${ea}${e}${ye}`,green:e=>`${ta}${e}${ye}`,yellow:e=>`${ra}${e}${ye}`,blue:e=>`${oa}${e}${ye}`,bold:e=>`${Zi}${e}${ye}`},_t=e=>e.replaceAll(/\*\*(.*?)\*\*/g,(t,r)=>ee.bold(r));var es=yr(or(),1);import{CloudFormationClient as Zn,DescribeStackResourcesCommand as eu,DescribeStacksCommand as tu,paginateListStacks as ru}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as ou,CreateInvalidationCommand as nu}from"@aws-sdk/client-cloudfront";import{ECSClient as su}from"@aws-sdk/client-ecs";import{S3Client as iu}from"@aws-sdk/client-s3";import{GetParameterCommand as au,PutParameterCommand as cu,SSMClient as lu}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as uu,STSClient as pu}from"@aws-sdk/client-sts";import{normalizeErrorString as du}from"@medplum/core";import mu from"node-fetch";import{readdirSync as fu}from"node:fs";import Zl from"node:readline";var Qe;function Ze(){Qe=Zl.createInterface({input:process.stdin,output:process.stdout})}function et(){Qe.close()}function c(e){Qe.write(e+`
|
|
5
5
|
`)}function v(e){c(`
|
|
6
6
|
`+e+`
|
|
7
|
-
`)}function N(e,t=""){return new Promise(r=>{Qe.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function tt(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await N(o)||r;if(t.includes(n))return n;c("Please choose one of the following options: "+t.join(", "))}}async function se(e,t,r){return parseInt(await tt(e,t.map(o=>o.toString()),r.toString()),10)}async function J(e){return(await tt(e,["y","n"])).toLowerCase()==="y"}async function ve(e){if(!await J(e))throw c("Exiting..."),new Error("User cancelled")}var rt=new Zn({}),hu=new ou({region:"us-east-1"}),nh=new su({}),be=new iu({}),gu="medplum:environment";async function nr(){let e=[],t=ru({client:rt},{StackStatusFilter:["CREATE_COMPLETE","CREATE_FAILED","CREATE_IN_PROGRESS","DELETE_FAILED","DELETE_IN_PROGRESS","IMPORT_COMPLETE","IMPORT_IN_PROGRESS","IMPORT_ROLLBACK_COMPLETE","IMPORT_ROLLBACK_FAILED","IMPORT_ROLLBACK_IN_PROGRESS","REVIEW_IN_PROGRESS","ROLLBACK_COMPLETE","ROLLBACK_FAILED","ROLLBACK_IN_PROGRESS","UPDATE_COMPLETE","UPDATE_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_FAILED","UPDATE_IN_PROGRESS","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_IN_PROGRESS"]});for await(let r of t)if(r.StackSummaries)for(let o of r.StackSummaries)e.push(o);return e}async function ie(e){let t=await nr();for(let r of t){let o=r.StackName,n=await sr(o);if(n?.tag===e)return n}}async function sr(e){let t={};if(await Qn(rt,e,t),await rt.config.region()!=="us-east-1")try{await Qn(new Zn({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function Qn(e,t,r){let o=new tu({StackName:t}),s=(await e.send(o))?.Stacks?.[0],i=s?.Tags?.find(l=>l.Key===gu);if(!i)return;let a=await e.send(new eu({StackName:t}));if(a.StackResources){e===rt&&(r.stack=s,r.tag=i.Value);for(let l of a.StackResources)yu(l,r)}}function yu(e,t){e.ResourceType==="AWS::ECS::Cluster"?t.ecsCluster=e:e.ResourceType==="AWS::ECS::Service"?t.ecsService=e:e.ResourceType==="AWS::S3::Bucket"&&e.LogicalResourceId?.startsWith("FrontEndAppBucket")?t.appBucket=e:e.ResourceType==="AWS::CloudFront::Distribution"&&e.LogicalResourceId?.startsWith("FrontEndAppDistribution")?t.appDistribution=e:e.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&e.LogicalResourceId?.startsWith("FrontEndOriginAccessIdentity")?t.appOriginAccessIdentity=e:e.ResourceType==="AWS::S3::Bucket"&&e.LogicalResourceId?.startsWith("StorageStorageBucket")?t.storageBucket=e:e.ResourceType==="AWS::CloudFront::Distribution"&&e.LogicalResourceId?.startsWith("StorageStorageDistribution")?t.storageDistribution=e:e.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&e.LogicalResourceId?.startsWith("StorageOriginAccessIdentity")&&(t.storageOriginAccessIdentity=e)}function ot(e){console.log(`Medplum Tag: ${e.tag}`),console.log(`Stack Name: ${e.stack?.StackName}`),console.log(`Stack ID: ${e.stack?.StackId}`),console.log(`Status: ${e.stack?.StackStatus}`),console.log(`ECS Cluster: ${e.ecsCluster?.PhysicalResourceId}`),console.log(`ECS Service: ${wu(e.ecsService)}`),console.log(`App Bucket: ${e.appBucket?.PhysicalResourceId}`),console.log(`App Distribution: ${e.appDistribution?.PhysicalResourceId}`),console.log(`App OAI: ${e.appOriginAccessIdentity?.PhysicalResourceId}`),console.log(`Storage Bucket: ${e.storageBucket?.PhysicalResourceId}`),console.log(`Storage Distribution: ${e.storageDistribution?.PhysicalResourceId}`),console.log(`Storage OAI: ${e.storageOriginAccessIdentity?.PhysicalResourceId}`)}function wu(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function nt(e){let t=await hu.send(new nu({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function st(e){let o=(await(await mu("https://api.github.com/repos/medplum/medplum/releases?per_page=100",{headers:{Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}})).json()).map(n=>n.tag_name.startsWith("v")?n.tag_name.slice(1):n.tag_name);return o.sort((n,s)=>es.compare(s,n)),e?o.slice(0,o.indexOf(e)):o}async function it(e,t,r){let o=new lu({region:e});for(let[n,s]of Object.entries(r)){let i=t+n,a=s.toString(),l=await Eu(o,i);l!==void 0&&l!==a&&(c(`Parameter "${i}" exists with different value.`),await ve(`Do you want to overwrite "${i}"?`)),await Su(o,i,a)}}async function Eu(e,t){let r=new au({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Su(e,t,r){let o=new cu({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}function X(e,t){if(console.log(`Config not found: ${e} (${M(e,t)})`),t){let o=Object.entries(t);if(o.length>0){console.log("Additional options:");for(let[n,s]of o)console.log(` ${n}: ${s}`)}}console.log();let r=fu(".",{withFileTypes:!0});if(r=r.filter(o=>o.isFile()&&o.name.startsWith("medplum.")&&o.name.endsWith(".json")).map(o=>o.name),r.length===0)console.log("No configs found");else{console.log("Available configs:");for(let o of r)console.log(` ${o.replaceAll("medplum.","").replaceAll(".config","").replaceAll(".server","").replaceAll(".json","").padEnd(40," ")} (${o})`)}}async function ae(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new pu,r=new uu({}),o=await t.send(r),n=await t.config.region();console.log("AWS Region: ",n),console.log("AWS Account ID: ",o.Account),console.log("AWS Account ARN: ",o.Arn),console.log("AWS User ID: ",o.UserId)}catch(t){console.log("Warning: Unable to get AWS account ID",du(t))}}async function ts(e){let t=await ie(e);if(!t)throw await ae(e),new Error(`Stack not found: ${e}`);ot(t)}import{ACMClient as ns,ListCertificatesCommand as Ru,RequestCertificateCommand as Au}from"@aws-sdk/client-acm";import{CloudFrontClient as Pu,CreatePublicKeyCommand as Iu}from"@aws-sdk/client-cloudfront";import{GetCallerIdentityCommand as vu,STSClient as bu}from"@aws-sdk/client-sts";import{normalizeErrorString as Cu}from"@medplum/core";import{generateKeyPairSync as Tu,randomUUID as rs}from"node:crypto";import{existsSync as Ou}from"node:fs";var xu=e=>`${e}DomainName`,ss=e=>`${e}SslCertArn`;async function is(){let e={apiPort:8103,region:"us-east-1"};Ze(),v("MEDPLUM"),c("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),c(""),c("Most Medplum infrastructure is deployed using the AWS CDK."),c("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),c("This tool will help you create those resources."),c(""),c("Upon completion, this tool will:"),c(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),c(" 2. Optionally generate an AWS CloudFront signing key"),c(" 3. Optionally request SSL certificates from AWS Certificate Manager"),c(" 4. Optionally write server config settings to AWS Parameter Store"),c(""),c("The Medplum infra config file is an input to the Medplum CDK."),c("The Medplum CDK will create and manage the necessary AWS resources."),c(""),c("We will ask a series of questions to generate your infra config file."),c("Some questions have predefined options in [square brackets]."),c("Some questions have default values in (parentheses), which you can accept by pressing Enter."),c("Press Ctrl+C at any time to exit.");let t=await $u(e.region);t||(c("It appears that you do not have AWS credentials configured."),c("AWS credentials are not strictly required, but will enable some additional features."),c("If you intend to use AWS credentials, please configure them now."),await ve("Do you want to continue without AWS credentials?")),v("ENVIRONMENT NAME"),c('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),c("The environment name is used in multiple places:"),c(" 1. As part of config file names (i.e., medplum.demo.config.json)"),c(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),c(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await N("What is your environment name?","demo"),c('Using environment name "'+e.name+'"...'),v("CONFIG FILE"),c("Medplum Infrastructure will create a config file in the current directory.");let r=await N("What is the config file name?",`medplum.${e.name}.config.json`);Ou(r)&&(c("Config file already exists."),await ve("Do you want to overwrite the config file?")),c('Using config file "'+r+'"...'),C(r,e),v("AWS REGION"),c("Most Medplum resources will be created in a single AWS region."),e.region=await N("Enter your AWS region:","us-east-1"),C(r,e),v("AWS ACCOUNT NUMBER"),c("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&c("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await N("What is your AWS account number?",t),C(r,e),v("STACK NAME"),c("Medplum will create a CloudFormation stack to manage AWS resources."),c("AWS CloudFormation stack names ");let o="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await N("Enter your CloudFormation stack name?",o),C(r,e),v("BASE DOMAIN NAME"),c("Please enter the base domain name for your Medplum deployment."),c(""),c("Medplum deploys multiple subdomains for various services."),c(""),c('For example, "api." for the REST API and "app." for the web application.'),c("The base domain name is the common suffix for all subdomains."),c(""),c('For example, if your base domain name is "example.com",'),c('then the REST API will be "api.example.com".'),c(""),c('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),c(""),c("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await N("Enter your base domain name:");C(r,e),v("SUPPORT EMAIL"),c("Medplum sends transactional emails to users."),c("For example, emails to new users or for password reset."),c("Medplum will use the support email address to send these emails."),c("Note that you must verify the support email address in SES.");let n=await N("Enter your support email address:");v("API DOMAIN NAME"),c("Medplum deploys a REST API for the backend services."),e.apiDomainName=await N("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,C(r,e),v("APP DOMAIN NAME"),c("Medplum deploys a web application for the user interface."),e.appDomainName=await N("Enter your web application domain name:","app."+e.domainName),C(r,e),v("STORAGE DOMAIN NAME"),c("Medplum deploys a storage service for file uploads."),e.storageDomainName=await N("Enter your storage domain name:","storage."+e.domainName),C(r,e),v("STORAGE BUCKET"),c("Medplum uses an S3 bucket to store binary content such as file uploads."),c("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await N("Enter your storage bucket name:",e.storageDomainName),C(r,e),v("MAX AVAILABILITY ZONES"),c("Medplum API servers can be deployed in multiple availability zones."),c("This provides redundancy and high availability."),c("However, it also increases the cost of the deployment."),c("If you want to use all availability zones, choose a large number such as 99."),c("If you want to restrict the number, for example to manage EIP limits,"),c("then choose a small number such as 2 or 3."),e.maxAzs=await se("Enter the maximum number of availability zones:",[2,3,99],2),v("DATABASE INSTANCES"),c("Medplum uses a relational database to store data."),c("Medplum can create a new RDS database as part of the CloudFormation stack,"),c("or can set up your own database and enter the database name, username, and password."),await J("Do you want to create a new RDS database as part of the CloudFormation stack?")?(c("Medplum will create a new RDS database as part of the CloudFormation stack."),c(""),c("If you need high availability, you can choose multiple instances."),c("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await se("Enter the number of database instances:",[1,2],1)):(c("Medplum will not create a new RDS database."),c("Please create a new RDS database and enter the database name, username, and password."),c('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),e.rdsSecretsArn="TODO"),C(r,e),v("SERVER INSTANCES"),c("Medplum uses AWS Fargate to run the API servers."),c("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),c("Fargate will automatically scale the number of servers up and down."),c("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await se("Enter the number of server instances:",[1,2,3,4,6,8],1),C(r,e),v("SERVER MEMORY"),c("You can choose the amount of memory for each server instance."),c("The default is 512 MB, which is sufficient for getting started."),c("Note that only certain CPU units are compatible with memory units."),c('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await se("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),C(r,e),v("SERVER CPU"),c("You can choose the amount of CPU for each server instance."),c("CPU is expressed as an integer using AWS CPU units"),c("The default is 256, which is sufficient for getting started."),c("Note that only certain CPU units are compatible with memory units."),c('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await se("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),C(r,e),v("SERVER IMAGE"),c("Medplum uses Docker images for the API servers."),c("You can choose the image to use for the servers."),c("Docker images can be loaded from either Docker Hub or AWS ECR."),c("The default is the latest Medplum release.");let s=(await st())[0]??"latest";e.serverImage=await N("Enter the server image:",`medplum/medplum-server:${s}`),C(r,e),v("SIGNING KEY"),c("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let i=await Du(e.region,e.stackName+"SigningKey");i?(e.signingKeyId=i.keyId,e.storagePublicKey=i.publicKey,C(r,e)):(c("Unable to generate signing key."),c("Please manually create a signing key and enter the key ID and public key in the config file."),c('You must set the "signingKeyId", "signingKey", and "signingKeyPassphrase" settings.')),v("SSL CERTIFICATES"),c("Medplum will now check for existing SSL certificates for the subdomains.");let a=await Nu(e.region);c("Found "+a.length+" certificate(s).");for(let{region:u,certName:h}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){c("");let m=await Lu(e,a,u,h);e[ss(h)]=m,C(r,e)}v("AWS PARAMETER STORE"),c("Medplum uses AWS Parameter Store to store sensitive configuration values."),c("These values will be encrypted at rest."),c(`The values will be stored in the "/medplum/${e.name}" path.`);let l={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,supportEmail:n};if(i&&(l.signingKeyId=i.keyId,l.signingKey=i.privateKey,l.signingKeyPassphrase=i.passphrase),c(JSON.stringify({...l,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await J("Do you want to store these values in AWS Parameter Store?"))await it(e.region,`/medplum/${e.name}/`,l);else{let u=M(e.name,{server:!0});C(u,l),c("Skipping AWS Parameter Store."),c(`Writing values to local config file: ${u}`),c("Please add these values to AWS Parameter Store manually.")}v("DONE!"),c("Medplum configuration complete."),c("You can now proceed to deploying the Medplum infrastructure with CDK."),c("Run:"),c(""),c(` npx cdk bootstrap -c config=${r}`),c(` npx cdk synth -c config=${r}`),e.region==="us-east-1"?c(` npx cdk deploy -c config=${r}`):c(` npx cdk deploy -c config=${r} --all`),c(""),c("See Medplum documentation for more information:"),c(""),c(" https://www.medplum.com/docs/self-hosting/install-on-aws"),c(""),et()}async function $u(e){try{let t=new bu({region:e}),r=new vu({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Nu(e){let t=await os(e);if(e!=="us-east-1"){let r=await os("us-east-1");t.push(...r)}return t}async function os(e){try{let t=new ns({region:e}),r=new Ru({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Lu(e,t,r,o){let n=e[xu(o)],s=t.find(a=>a.CertificateArn?.includes(r)&&a.DomainName===n);if(s)return c(`Found existing certificate for "${n}" in "${r}.`),s.CertificateArn;if(c(`No existing certificate found for "${n}" in "${r}.`),!await J("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${ss(o)}" setting.`),"TODO";let i=await ku(r,n);return c("Certificate ARN: "+i),i}async function ku(e,t){try{let r=await tt("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new ns({region:e}),n=new Au({DomainName:t,ValidationMethod:r.toUpperCase()});return(await o.send(n)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function Du(e,t){let r=rs(),o=Tu("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new Pu({region:e}).send(new Iu({PublicKeyConfig:{Name:t,CallerReference:rs(),EncodedKey:o.publicKey}}))).PublicKey?.Id,publicKey:o.publicKey,privateKey:o.privateKey,passphrase:r}}catch(n){console.log("Error: Unable to create signing key: ",Cu(n));return}}async function as(){let e=await nr();for(let t of e){let r=t.StackName,o=await sr(r);o&&(ot(o),console.log(""))}}import{PutObjectCommand as Mu}from"@aws-sdk/client-s3";import{ContentType as B}from"@medplum/core";import _u from"fast-glob";import cs from"node-fetch";import{createReadStream as Uu,mkdtempSync as ju,readdirSync as Fu,readFileSync as Bu,rmSync as Wu,writeFileSync as Ku}from"node:fs";import{tmpdir as qu}from"node:os";import{join as at,sep as Hu}from"node:path";import{pipeline as Gu}from"node:stream/promises";async function ls(e,t){let r=j(e,t);if(!r)throw X(e,t),new Error(`Config not found: ${e}`);let o=await ie(e);if(!o)throw await ae(e),new Error(`Stack not found: ${e}`);let n=o.appBucket;if(!n)throw new Error(`App bucket not found for stack ${e}`);let s;if(t.tarPath)s=t.tarPath;else{let i=t?.toVersion??"latest";s=await Ju("@medplum/app",i)}us(s,{MEDPLUM_BASE_URL:r.baseUrl,MEDPLUM_CLIENT_ID:r.clientId??"",GOOGLE_CLIENT_ID:r.googleClientId??"",RECAPTCHA_SITE_KEY:r.recaptchaSiteKey??"",MEDPLUM_REGISTER_ENABLED:r.registerEnabled?"true":"false"}),await zu(s,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await nt(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Vu(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await cs(r)).json()}async function Ju(e,t){let o=(await Vu(e,t)).dist.tarball,n=ju(at(qu(),"tarball-"));try{let s=await cs(o),i=Jr(n);return await Gu(s.body,i),at(n,"package","dist")}catch(s){throw Wu(n,{recursive:!0,force:!0}),s}}function us(e,t){for(let r of Fu(e,{withFileTypes:!0})){let o=at(e,r.name);r.isDirectory()?us(o,t):r.isFile()&&o.endsWith(".js")&&Xu(o,t)}}function Xu(e,t){let r=Bu(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);Ku(e,r)}async function zu(e,t,r){let o=[["assets/**/*.css",B.CSS,!0],["assets/**/*.css.map",B.JSON,!0],["assets/**/*.js",B.JAVASCRIPT,!0],["assets/**/*.js.map",B.JSON,!0],["assets/**/*.txt",B.TEXT,!0],["assets/**/*.ico",B.FAVICON,!0],["img/**/*.png",B.PNG,!0],["img/**/*.svg",B.SVG,!0],["robots.txt",B.TEXT,!0],["index.html",B.HTML,!1]];for(let n of o)await Yu({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function Yu(e){let t=_u.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await Qu(at(e.rootDir,r),e)}async function Qu(e,t){let r=Uu(e),o=e.substring(t.rootDir.length+1).split(Hu).join("/"),n={Bucket:t.bucketName,Key:o,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${o} to ${t.bucketName}...`),t.dryrun||await be.send(new Mu(n))}import{GetBucketPolicyCommand as Zu,PutBucketPolicyCommand as ep}from"@aws-sdk/client-s3";async function ds(e,t){if(!j(e,t))throw X(e,t),new Error(`Config not found: ${e}`);let o=await ie(e);if(!o)throw await ae(e),new Error(`Stack not found: ${e}`);await ps("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await ps("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function ps(e,t,r,o,n){if(!t?.PhysicalResourceId)throw new Error(`${e} bucket not found`);if(!r?.PhysicalResourceId)throw new Error(`${e} distribution not found`);if(!o?.PhysicalResourceId)throw new Error(`${e} OAI not found`);let s=t.PhysicalResourceId,i=o.PhysicalResourceId,a=await tp(s);if(op(a,s,i))throw new Error(`${e} bucket already has policy statement`);np(a,s,i),console.log(`${e} bucket policy:`),console.log(JSON.stringify(a,void 0,2)),n.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await rp(s,a),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await nt(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function tp(e){let t=await be.send(new Zu({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function rp(e,t){await be.send(new ep({Bucket:e,Policy:JSON.stringify(t)}))}function op(e,t,r){return!!e?.Statement?.some(o=>o?.Effect==="Allow"&&o?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Array.isArray(o?.Action)&&o?.Action?.includes("s3:GetObject*")&&o?.Action?.includes("s3:GetBucket*")&&o?.Action?.includes("s3:List*")&&Array.isArray(o?.Resource)&&o?.Resource?.includes(`arn:aws:s3:::${t}`)&&o?.Resource?.includes(`arn:aws:s3:::${t}/*`))}function np(e,t,r){e.Version||(e.Version="2012-10-17"),e.Statement||(e.Statement=[]),e.Statement.push({Effect:"Allow",Principal:{AWS:`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`},Action:["s3:GetObject*","s3:GetBucket*","s3:List*"],Resource:[`arn:aws:s3:::${t}`,`arn:aws:s3:::${t}/*`]})}async function ms(e,t){try{Ze();let r=j(e,t);if(!r)throw X(e,t),new Error(`Config not found: ${e}`);let o=Vr(e)??{};if(!t.yes&&Object.keys(o).length===0){let n=M(e,{server:!0});if(console.log(ee.yellow(`Config file ${n} not found!`)),!await J("Do you want to proceed?")){console.log(ee.red(`Run Aborted, please ensure ${n} is present and try again.`));return}}sp(r,o),ap(r,o),c("Medplum uses AWS Parameter Store to store sensitive configuration values."),c("These values will be encrypted at rest."),c(`The values will be stored in the "/medplum/${r.name}" path.`),c(JSON.stringify({...o,signingKey:"****",signingKeyPassphrase:"****"},null,2)),t.dryrun?console.log(ee.yellow("Dry run - skipping updates!")):(t.yes||await J("Do you want to store these values in AWS Parameter Store?"))&&await it(r.region,`/medplum/${r.name}/`,o)}finally{et()}}function sp(e,t){ct(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),ct(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),ct(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),ct(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function ct(e,t,r){if(ip(e,t))throw new Error(r)}function ip(e,t){return e!==void 0&&t!==void 0&&e!==t}function ap(e,t){e.apiPort&&(t.port=e.apiPort),e.baseUrl&&(t.baseUrl=e.baseUrl),e.appDomainName&&(t.appBaseUrl=`https://${e.appDomainName}/`),e.storageDomainName&&(t.storageBaseUrl=`https://${e.storageDomainName}/`)}var ce=yr(or(),1);import{spawnSync as cp}from"node:child_process";async function hs(e,t){let r=await R(t),o=j(e,t);if(!o)throw console.log(`Configuration file ${M(e)} not found`),X(e,t),new Error(`Config not found: ${e}`);let n=o.serverImage.lastIndexOf(":"),s=o.serverImage.slice(0,n),i=await lp(r,o),a=await fs(i);for(;a;){if(t.toVersion&&ce.gt(a,t.toVersion)){console.log(`Skipping update to v${a}`);break}console.log(`Performing update to v${a}`),o.serverImage=`${s}:${a}`,up(e,o),await r.startAsyncRequest("/admin/super/migrate"),a=await fs(a)}}async function lp(e,t){let r=t.serverImage.lastIndexOf(":"),o=t.serverImage.slice(r+1);if(o==="latest"){o=(await e.get("/healthcheck")).version;let s=o.indexOf("-");s>-1&&(o=o.slice(0,s))}return o}async function fs(e,t){let r=await st(e),o=r[0];return r.filter(n=>n===o||n===t||ce.gte(n,ce.inc(e,"minor"))).pop()}function up(e,t){let r=M(e);C(r,t);let o=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+o);let n=cp(o,{stdio:"inherit"});if(n.status!==0)throw new Error(`Deploy of ${t.serverImage} failed (exit code ${n.status}): ${n.stderr}`);console.log(n.stdout)}function gs(){let e=new g("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(is),e.command("list").description("List Medplum AWS CloudFormation stacks").action(as),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(ts),e.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(_t(`Update the AWS Parameter Store config values.
|
|
7
|
+
`)}function N(e,t=""){return new Promise(r=>{Qe.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function tt(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await N(o)||r;if(t.includes(n))return n;c("Please choose one of the following options: "+t.join(", "))}}async function se(e,t,r){return Number.parseInt(await tt(e,t.map(o=>o.toString()),r.toString()),10)}async function J(e){return(await tt(e,["y","n"])).toLowerCase()==="y"}async function ve(e){if(!await J(e))throw c("Exiting..."),new Error("User cancelled")}var rt=new Zn({}),hu=new ou({region:"us-east-1"}),nh=new su({}),be=new iu({}),gu="medplum:environment";async function nr(){let e=[],t=ru({client:rt},{StackStatusFilter:["CREATE_COMPLETE","CREATE_FAILED","CREATE_IN_PROGRESS","DELETE_FAILED","DELETE_IN_PROGRESS","IMPORT_COMPLETE","IMPORT_IN_PROGRESS","IMPORT_ROLLBACK_COMPLETE","IMPORT_ROLLBACK_FAILED","IMPORT_ROLLBACK_IN_PROGRESS","REVIEW_IN_PROGRESS","ROLLBACK_COMPLETE","ROLLBACK_FAILED","ROLLBACK_IN_PROGRESS","UPDATE_COMPLETE","UPDATE_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_FAILED","UPDATE_IN_PROGRESS","UPDATE_ROLLBACK_COMPLETE","UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS","UPDATE_ROLLBACK_FAILED","UPDATE_ROLLBACK_IN_PROGRESS"]});for await(let r of t)if(r.StackSummaries)for(let o of r.StackSummaries)e.push(o);return e}async function ie(e){let t=await nr();for(let r of t){let o=r.StackName,n=await sr(o);if(n?.tag===e)return n}}async function sr(e){let t={};if(await Qn(rt,e,t),await rt.config.region()!=="us-east-1")try{await Qn(new Zn({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function Qn(e,t,r){let o=new tu({StackName:t}),s=(await e.send(o))?.Stacks?.[0],i=s?.Tags?.find(l=>l.Key===gu);if(!i)return;let a=await e.send(new eu({StackName:t}));if(a.StackResources){e===rt&&(r.stack=s,r.tag=i.Value);for(let l of a.StackResources)yu(l,r)}}function yu(e,t){e.ResourceType==="AWS::ECS::Cluster"?t.ecsCluster=e:e.ResourceType==="AWS::ECS::Service"?t.ecsService=e:e.ResourceType==="AWS::S3::Bucket"&&e.LogicalResourceId?.startsWith("FrontEndAppBucket")?t.appBucket=e:e.ResourceType==="AWS::CloudFront::Distribution"&&e.LogicalResourceId?.startsWith("FrontEndAppDistribution")?t.appDistribution=e:e.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&e.LogicalResourceId?.startsWith("FrontEndOriginAccessIdentity")?t.appOriginAccessIdentity=e:e.ResourceType==="AWS::S3::Bucket"&&e.LogicalResourceId?.startsWith("StorageStorageBucket")?t.storageBucket=e:e.ResourceType==="AWS::CloudFront::Distribution"&&e.LogicalResourceId?.startsWith("StorageStorageDistribution")?t.storageDistribution=e:e.ResourceType==="AWS::CloudFront::CloudFrontOriginAccessIdentity"&&e.LogicalResourceId?.startsWith("StorageOriginAccessIdentity")&&(t.storageOriginAccessIdentity=e)}function ot(e){console.log(`Medplum Tag: ${e.tag}`),console.log(`Stack Name: ${e.stack?.StackName}`),console.log(`Stack ID: ${e.stack?.StackId}`),console.log(`Status: ${e.stack?.StackStatus}`),console.log(`ECS Cluster: ${e.ecsCluster?.PhysicalResourceId}`),console.log(`ECS Service: ${wu(e.ecsService)}`),console.log(`App Bucket: ${e.appBucket?.PhysicalResourceId}`),console.log(`App Distribution: ${e.appDistribution?.PhysicalResourceId}`),console.log(`App OAI: ${e.appOriginAccessIdentity?.PhysicalResourceId}`),console.log(`Storage Bucket: ${e.storageBucket?.PhysicalResourceId}`),console.log(`Storage Distribution: ${e.storageDistribution?.PhysicalResourceId}`),console.log(`Storage OAI: ${e.storageOriginAccessIdentity?.PhysicalResourceId}`)}function wu(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function nt(e){let t=await hu.send(new nu({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function st(e){let o=(await(await mu("https://api.github.com/repos/medplum/medplum/releases?per_page=100",{headers:{Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28"}})).json()).map(n=>n.tag_name.startsWith("v")?n.tag_name.slice(1):n.tag_name);return o.sort((n,s)=>es.compare(s,n)),e?o.slice(0,o.indexOf(e)):o}async function it(e,t,r){let o=new lu({region:e});for(let[n,s]of Object.entries(r)){let i=t+n,a=s.toString(),l=await Eu(o,i);l!==void 0&&l!==a&&(c(`Parameter "${i}" exists with different value.`),await ve(`Do you want to overwrite "${i}"?`)),await Su(o,i,a)}}async function Eu(e,t){let r=new au({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Su(e,t,r){let o=new cu({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}function X(e,t){if(console.log(`Config not found: ${e} (${M(e,t)})`),t){let o=Object.entries(t);if(o.length>0){console.log("Additional options:");for(let[n,s]of o)console.log(` ${n}: ${s}`)}}console.log();let r=fu(".",{withFileTypes:!0});if(r=r.filter(o=>o.isFile()&&o.name.startsWith("medplum.")&&o.name.endsWith(".json")).map(o=>o.name),r.length===0)console.log("No configs found");else{console.log("Available configs:");for(let o of r)console.log(` ${o.replaceAll("medplum.","").replaceAll(".config","").replaceAll(".server","").replaceAll(".json","").padEnd(40," ")} (${o})`)}}async function ae(e){console.log(`Stack not found: ${e}`),console.log();try{let t=new pu,r=new uu({}),o=await t.send(r),n=await t.config.region();console.log("AWS Region: ",n),console.log("AWS Account ID: ",o.Account),console.log("AWS Account ARN: ",o.Arn),console.log("AWS User ID: ",o.UserId)}catch(t){console.log("Warning: Unable to get AWS account ID",du(t))}}async function ts(e){let t=await ie(e);if(!t)throw await ae(e),new Error(`Stack not found: ${e}`);ot(t)}import{ACMClient as ns,ListCertificatesCommand as Ru,RequestCertificateCommand as Au}from"@aws-sdk/client-acm";import{CloudFrontClient as Pu,CreatePublicKeyCommand as Iu}from"@aws-sdk/client-cloudfront";import{GetCallerIdentityCommand as vu,STSClient as bu}from"@aws-sdk/client-sts";import{normalizeErrorString as Cu}from"@medplum/core";import{generateKeyPairSync as Tu,randomUUID as rs}from"node:crypto";import{existsSync as Ou}from"node:fs";var xu=e=>`${e}DomainName`,ss=e=>`${e}SslCertArn`;async function is(){let e={apiPort:8103,region:"us-east-1"};Ze(),v("MEDPLUM"),c("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),c(""),c("Most Medplum infrastructure is deployed using the AWS CDK."),c("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),c("This tool will help you create those resources."),c(""),c("Upon completion, this tool will:"),c(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),c(" 2. Optionally generate an AWS CloudFront signing key"),c(" 3. Optionally request SSL certificates from AWS Certificate Manager"),c(" 4. Optionally write server config settings to AWS Parameter Store"),c(""),c("The Medplum infra config file is an input to the Medplum CDK."),c("The Medplum CDK will create and manage the necessary AWS resources."),c(""),c("We will ask a series of questions to generate your infra config file."),c("Some questions have predefined options in [square brackets]."),c("Some questions have default values in (parentheses), which you can accept by pressing Enter."),c("Press Ctrl+C at any time to exit.");let t=await $u(e.region);t||(c("It appears that you do not have AWS credentials configured."),c("AWS credentials are not strictly required, but will enable some additional features."),c("If you intend to use AWS credentials, please configure them now."),await ve("Do you want to continue without AWS credentials?")),v("ENVIRONMENT NAME"),c('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),c("The environment name is used in multiple places:"),c(" 1. As part of config file names (i.e., medplum.demo.config.json)"),c(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),c(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await N("What is your environment name?","demo"),c('Using environment name "'+e.name+'"...'),v("CONFIG FILE"),c("Medplum Infrastructure will create a config file in the current directory.");let r=await N("What is the config file name?",`medplum.${e.name}.config.json`);Ou(r)&&(c("Config file already exists."),await ve("Do you want to overwrite the config file?")),c('Using config file "'+r+'"...'),C(r,e),v("AWS REGION"),c("Most Medplum resources will be created in a single AWS region."),e.region=await N("Enter your AWS region:","us-east-1"),C(r,e),v("AWS ACCOUNT NUMBER"),c("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&c("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await N("What is your AWS account number?",t),C(r,e),v("STACK NAME"),c("Medplum will create a CloudFormation stack to manage AWS resources."),c("AWS CloudFormation stack names ");let o="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await N("Enter your CloudFormation stack name?",o),C(r,e),v("BASE DOMAIN NAME"),c("Please enter the base domain name for your Medplum deployment."),c(""),c("Medplum deploys multiple subdomains for various services."),c(""),c('For example, "api." for the REST API and "app." for the web application.'),c("The base domain name is the common suffix for all subdomains."),c(""),c('For example, if your base domain name is "example.com",'),c('then the REST API will be "api.example.com".'),c(""),c('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),c(""),c("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await N("Enter your base domain name:");C(r,e),v("SUPPORT EMAIL"),c("Medplum sends transactional emails to users."),c("For example, emails to new users or for password reset."),c("Medplum will use the support email address to send these emails."),c("Note that you must verify the support email address in SES.");let n=await N("Enter your support email address:");v("API DOMAIN NAME"),c("Medplum deploys a REST API for the backend services."),e.apiDomainName=await N("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,C(r,e),v("APP DOMAIN NAME"),c("Medplum deploys a web application for the user interface."),e.appDomainName=await N("Enter your web application domain name:","app."+e.domainName),C(r,e),v("STORAGE DOMAIN NAME"),c("Medplum deploys a storage service for file uploads."),e.storageDomainName=await N("Enter your storage domain name:","storage."+e.domainName),C(r,e),v("STORAGE BUCKET"),c("Medplum uses an S3 bucket to store binary content such as file uploads."),c("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await N("Enter your storage bucket name:",e.storageDomainName),C(r,e),v("MAX AVAILABILITY ZONES"),c("Medplum API servers can be deployed in multiple availability zones."),c("This provides redundancy and high availability."),c("However, it also increases the cost of the deployment."),c("If you want to use all availability zones, choose a large number such as 99."),c("If you want to restrict the number, for example to manage EIP limits,"),c("then choose a small number such as 2 or 3."),e.maxAzs=await se("Enter the maximum number of availability zones:",[2,3,99],2),v("DATABASE INSTANCES"),c("Medplum uses a relational database to store data."),c("Medplum can create a new RDS database as part of the CloudFormation stack,"),c("or can set up your own database and enter the database name, username, and password."),await J("Do you want to create a new RDS database as part of the CloudFormation stack?")?(c("Medplum will create a new RDS database as part of the CloudFormation stack."),c(""),c("If you need high availability, you can choose multiple instances."),c("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await se("Enter the number of database instances:",[1,2],1)):(c("Medplum will not create a new RDS database."),c("Please create a new RDS database and enter the database name, username, and password."),c('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),e.rdsSecretsArn="TODO"),C(r,e),v("SERVER INSTANCES"),c("Medplum uses AWS Fargate to run the API servers."),c("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),c("Fargate will automatically scale the number of servers up and down."),c("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await se("Enter the number of server instances:",[1,2,3,4,6,8],1),C(r,e),v("SERVER MEMORY"),c("You can choose the amount of memory for each server instance."),c("The default is 512 MB, which is sufficient for getting started."),c("Note that only certain CPU units are compatible with memory units."),c('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await se("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),C(r,e),v("SERVER CPU"),c("You can choose the amount of CPU for each server instance."),c("CPU is expressed as an integer using AWS CPU units"),c("The default is 256, which is sufficient for getting started."),c("Note that only certain CPU units are compatible with memory units."),c('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await se("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),C(r,e),v("SERVER IMAGE"),c("Medplum uses Docker images for the API servers."),c("You can choose the image to use for the servers."),c("Docker images can be loaded from either Docker Hub or AWS ECR."),c("The default is the latest Medplum release.");let s=(await st())[0]??"latest";e.serverImage=await N("Enter the server image:",`medplum/medplum-server:${s}`),C(r,e),v("SIGNING KEY"),c("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let i=await Du(e.region,e.stackName+"SigningKey");i?(e.signingKeyId=i.keyId,e.storagePublicKey=i.publicKey,C(r,e)):(c("Unable to generate signing key."),c("Please manually create a signing key and enter the key ID and public key in the config file."),c('You must set the "signingKeyId", "signingKey", and "signingKeyPassphrase" settings.')),v("SSL CERTIFICATES"),c("Medplum will now check for existing SSL certificates for the subdomains.");let a=await Nu(e.region);c("Found "+a.length+" certificate(s).");for(let{region:u,certName:h}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){c("");let m=await Lu(e,a,u,h);e[ss(h)]=m,C(r,e)}v("AWS PARAMETER STORE"),c("Medplum uses AWS Parameter Store to store sensitive configuration values."),c("These values will be encrypted at rest."),c(`The values will be stored in the "/medplum/${e.name}" path.`);let l={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,supportEmail:n};if(i&&(l.signingKeyId=i.keyId,l.signingKey=i.privateKey,l.signingKeyPassphrase=i.passphrase),c(JSON.stringify({...l,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await J("Do you want to store these values in AWS Parameter Store?"))await it(e.region,`/medplum/${e.name}/`,l);else{let u=M(e.name,{server:!0});C(u,l),c("Skipping AWS Parameter Store."),c(`Writing values to local config file: ${u}`),c("Please add these values to AWS Parameter Store manually.")}v("DONE!"),c("Medplum configuration complete."),c("You can now proceed to deploying the Medplum infrastructure with CDK."),c("Run:"),c(""),c(` npx cdk bootstrap -c config=${r}`),c(` npx cdk synth -c config=${r}`),e.region==="us-east-1"?c(` npx cdk deploy -c config=${r}`):c(` npx cdk deploy -c config=${r} --all`),c(""),c("See Medplum documentation for more information:"),c(""),c(" https://www.medplum.com/docs/self-hosting/install-on-aws"),c(""),et()}async function $u(e){try{let t=new bu({region:e}),r=new vu({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Nu(e){let t=await os(e);if(e!=="us-east-1"){let r=await os("us-east-1");t.push(...r)}return t}async function os(e){try{let t=new ns({region:e}),r=new Ru({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Lu(e,t,r,o){let n=e[xu(o)],s=t.find(a=>a.CertificateArn?.includes(r)&&a.DomainName===n);if(s)return c(`Found existing certificate for "${n}" in "${r}.`),s.CertificateArn;if(c(`No existing certificate found for "${n}" in "${r}.`),!await J("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${ss(o)}" setting.`),"TODO";let i=await ku(r,n);return c("Certificate ARN: "+i),i}async function ku(e,t){try{let r=await tt("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new ns({region:e}),n=new Au({DomainName:t,ValidationMethod:r.toUpperCase()});return(await o.send(n)).CertificateArn}catch(r){return console.log("Error: Unable to request certificate",r.message),"TODO"}}async function Du(e,t){let r=rs(),o=Tu("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new Pu({region:e}).send(new Iu({PublicKeyConfig:{Name:t,CallerReference:rs(),EncodedKey:o.publicKey}}))).PublicKey?.Id,publicKey:o.publicKey,privateKey:o.privateKey,passphrase:r}}catch(n){console.log("Error: Unable to create signing key: ",Cu(n));return}}async function as(){let e=await nr();for(let t of e){let r=t.StackName,o=await sr(r);o&&(ot(o),console.log(""))}}import{PutObjectCommand as Mu}from"@aws-sdk/client-s3";import{ContentType as B}from"@medplum/core";import _u from"fast-glob";import cs from"node-fetch";import{createReadStream as Uu,mkdtempSync as ju,readdirSync as Fu,readFileSync as Bu,rmSync as Wu,writeFileSync as Ku}from"node:fs";import{tmpdir as qu}from"node:os";import{join as at,sep as Hu}from"node:path";import{pipeline as Gu}from"node:stream/promises";async function ls(e,t){let r=j(e,t);if(!r)throw X(e,t),new Error(`Config not found: ${e}`);let o=await ie(e);if(!o)throw await ae(e),new Error(`Stack not found: ${e}`);let n=o.appBucket;if(!n)throw new Error(`App bucket not found for stack ${e}`);let s;if(t.tarPath)s=t.tarPath;else{let i=t?.toVersion??"latest";s=await Ju("@medplum/app",i)}us(s,{MEDPLUM_BASE_URL:r.baseUrl,MEDPLUM_CLIENT_ID:r.clientId??"",GOOGLE_CLIENT_ID:r.googleClientId??"",RECAPTCHA_SITE_KEY:r.recaptchaSiteKey??"",MEDPLUM_REGISTER_ENABLED:r.registerEnabled?"true":"false"}),await zu(s,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await nt(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Vu(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await cs(r)).json()}async function Ju(e,t){let o=(await Vu(e,t)).dist.tarball,n=ju(at(qu(),"tarball-"));try{let s=await cs(o),i=Jr(n);return await Gu(s.body,i),at(n,"package","dist")}catch(s){throw Wu(n,{recursive:!0,force:!0}),s}}function us(e,t){for(let r of Fu(e,{withFileTypes:!0})){let o=at(e,r.name);r.isDirectory()?us(o,t):r.isFile()&&o.endsWith(".js")&&Xu(o,t)}}function Xu(e,t){let r=Bu(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);Ku(e,r)}async function zu(e,t,r){let o=[["assets/**/*.css",B.CSS,!0],["assets/**/*.css.map",B.JSON,!0],["assets/**/*.js",B.JAVASCRIPT,!0],["assets/**/*.js.map",B.JSON,!0],["assets/**/*.txt",B.TEXT,!0],["assets/**/*.ico",B.FAVICON,!0],["img/**/*.png",B.PNG,!0],["img/**/*.svg",B.SVG,!0],["robots.txt",B.TEXT,!0],["index.html",B.HTML,!1]];for(let n of o)await Yu({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function Yu(e){let t=_u.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await Qu(at(e.rootDir,r),e)}async function Qu(e,t){let r=Uu(e),o=e.substring(t.rootDir.length+1).split(Hu).join("/"),n={Bucket:t.bucketName,Key:o,Body:r,ContentType:t.contentType,CacheControl:t.cached?"public, max-age=31536000":"no-cache, no-store, must-revalidate"};console.log(`Uploading ${o} to ${t.bucketName}...`),t.dryrun||await be.send(new Mu(n))}import{GetBucketPolicyCommand as Zu,PutBucketPolicyCommand as ep}from"@aws-sdk/client-s3";async function ds(e,t){if(!j(e,t))throw X(e,t),new Error(`Config not found: ${e}`);let o=await ie(e);if(!o)throw await ae(e),new Error(`Stack not found: ${e}`);await ps("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await ps("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function ps(e,t,r,o,n){if(!t?.PhysicalResourceId)throw new Error(`${e} bucket not found`);if(!r?.PhysicalResourceId)throw new Error(`${e} distribution not found`);if(!o?.PhysicalResourceId)throw new Error(`${e} OAI not found`);let s=t.PhysicalResourceId,i=o.PhysicalResourceId,a=await tp(s);if(op(a,s,i))throw new Error(`${e} bucket already has policy statement`);np(a,s,i),console.log(`${e} bucket policy:`),console.log(JSON.stringify(a,void 0,2)),n.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await rp(s,a),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await nt(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function tp(e){let t=await be.send(new Zu({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function rp(e,t){await be.send(new ep({Bucket:e,Policy:JSON.stringify(t)}))}function op(e,t,r){return!!e?.Statement?.some(o=>o?.Effect==="Allow"&&o?.Principal?.AWS===`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`&&Array.isArray(o?.Action)&&o?.Action?.includes("s3:GetObject*")&&o?.Action?.includes("s3:GetBucket*")&&o?.Action?.includes("s3:List*")&&Array.isArray(o?.Resource)&&o?.Resource?.includes(`arn:aws:s3:::${t}`)&&o?.Resource?.includes(`arn:aws:s3:::${t}/*`))}function np(e,t,r){e.Version||(e.Version="2012-10-17"),e.Statement||(e.Statement=[]),e.Statement.push({Effect:"Allow",Principal:{AWS:`arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${r}`},Action:["s3:GetObject*","s3:GetBucket*","s3:List*"],Resource:[`arn:aws:s3:::${t}`,`arn:aws:s3:::${t}/*`]})}async function ms(e,t){try{Ze();let r=j(e,t);if(!r)throw X(e,t),new Error(`Config not found: ${e}`);let o=Vr(e)??{};if(!t.yes&&Object.keys(o).length===0){let n=M(e,{server:!0});if(console.log(ee.yellow(`Config file ${n} not found!`)),!await J("Do you want to proceed?")){console.log(ee.red(`Run Aborted, please ensure ${n} is present and try again.`));return}}sp(r,o),ap(r,o),c("Medplum uses AWS Parameter Store to store sensitive configuration values."),c("These values will be encrypted at rest."),c(`The values will be stored in the "/medplum/${r.name}" path.`),c(JSON.stringify({...o,signingKey:"****",signingKeyPassphrase:"****"},null,2)),t.dryrun?console.log(ee.yellow("Dry run - skipping updates!")):(t.yes||await J("Do you want to store these values in AWS Parameter Store?"))&&await it(r.region,`/medplum/${r.name}/`,o)}finally{et()}}function sp(e,t){ct(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),ct(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),ct(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),ct(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function ct(e,t,r){if(ip(e,t))throw new Error(r)}function ip(e,t){return e!==void 0&&t!==void 0&&e!==t}function ap(e,t){e.apiPort&&(t.port=e.apiPort),e.baseUrl&&(t.baseUrl=e.baseUrl),e.appDomainName&&(t.appBaseUrl=`https://${e.appDomainName}/`),e.storageDomainName&&(t.storageBaseUrl=`https://${e.storageDomainName}/`)}var ce=yr(or(),1);import{spawnSync as cp}from"node:child_process";async function hs(e,t){let r=await R(t),o=j(e,t);if(!o)throw console.log(`Configuration file ${M(e)} not found`),X(e,t),new Error(`Config not found: ${e}`);let n=o.serverImage.lastIndexOf(":"),s=o.serverImage.slice(0,n),i=await lp(r,o),a=await fs(i);for(;a;){if(t.toVersion&&ce.gt(a,t.toVersion)){console.log(`Skipping update to v${a}`);break}console.log(`Performing update to v${a}`),o.serverImage=`${s}:${a}`,up(e,o),await r.startAsyncRequest("/admin/super/migrate"),a=await fs(a)}}async function lp(e,t){let r=t.serverImage.lastIndexOf(":"),o=t.serverImage.slice(r+1);if(o==="latest"){o=(await e.get("/healthcheck")).version;let s=o.indexOf("-");s>-1&&(o=o.slice(0,s))}return o}async function fs(e,t){let r=await st(e),o=r[0];return r.filter(n=>n===o||n===t||ce.gte(n,ce.inc(e,"minor"))).pop()}function up(e,t){let r=M(e);C(r,t);let o=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+o);let n=cp(o,{stdio:"inherit"});if(n.status!==0)throw new Error(`Deploy of ${t.serverImage} failed (exit code ${n.status}): ${n.stderr}`);console.log(n.stdout)}function gs(){let e=new g("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(is),e.command("list").description("List Medplum AWS CloudFormation stacks").action(as),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(ts),e.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(_t(`Update the AWS Parameter Store config values.
|
|
8
8
|
|
|
9
9
|
Configuration values come from a file named **medplum.<tag>.config.server.json** where **<tag>** is the Medplum stack tag.
|
|
10
10
|
|