@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/cjs/index.cjs
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 Oo(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{xo(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 ua(e){let t=[];for(let r of e.entry??[]){if(!r.resource)throw new Error("No Parameter resource found in entry");t.push(pa(r.resource))}return t}function pa(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 da(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=ma(s,i);r[s]=a}return r}function ma(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 fa(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(!(0,ce.isUUID)(r))throw new Error(`Input '${r}' is not a valid agentId`);return{type:"ids",ids:e}}if(t.criteria)return xo(t.criteria),{type:"criteria",criteria:t.criteria};throw new Error("Either an [agentId...] arg or a --criteria <criteria> flag is required")}function xo(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 `=`")})}var F=require("@medplum/core"),$o=require("node:child_process"),No=require("node:http"),Lo=require("node:os");var ko=F.MEDPLUM_CLI_CLIENT_ID,Do="http://localhost:9615",rr=new g("login"),or=new g("whoami"),nr=new g("token");rr.action(async e=>{let t=e.profile??"default",r=nt(t,e),o=await R(e,!1);await ha(o,r)});or.action(async e=>{let t=await R(e);wa(t)});nr.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 ha(e,t){switch(t?.authType??"authorization-code"){case"authorization-code":await Ea(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 Ao(e,t);break;case"jwt-assertion":await Po(e,t);break}}async function ga(e){let t=(0,No.createServer)(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":F.ContentType.TEXT}),o.end("OK");return}if(n.pathname==="/"&&s)try{let i=await e.processCode(s,{clientId:ko,redirectUri:Do});o.writeHead(200,{"Content-Type":F.ContentType.TEXT}),o.end(`Signed in as ${(0,F.getDisplayString)(i)}. You may close this window.`)}catch(i){o.writeHead(400,{"Content-Type":F.ContentType.TEXT}),o.end(`Error: ${(0,F.normalizeErrorString)(i)}`)}finally{t.close(),process.exit(0)}else o.writeHead(404,{"Content-Type":F.ContentType.TEXT}),o.end("Not found")}).listen(9615)}async function ya(e){let t=(0,Lo.platform)(),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)=>{(0,$o.exec)(r,(s,i,a)=>{if(s){n(s);return}if(a){n(new Error("Could not open browser: "+a));return}o()})})}function wa(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 Ea(e){await ga(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",ko),t.searchParams.set("redirect_uri",Do),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await ya(t.toString())}var De="\x1B[0m",Sa="\x1B[1m",Ra="\x1B[31m",Aa="\x1B[32m",Pa="\x1B[33m",Ia="\x1B[34m",ue={red:e=>`${Ra}${e}${De}`,green:e=>`${Aa}${e}${De}`,yellow:e=>`${Pa}${e}${De}`,blue:e=>`${Ia}${e}${De}`,bold:e=>`${Sa}${e}${De}`},sr=e=>e.replaceAll(/\*\*(.*?)\*\*/g,(t,r)=>ue.bold(r));var Q=require("@aws-sdk/client-cloudformation"),Pt=require("@aws-sdk/client-cloudfront"),Cs=require("@aws-sdk/client-ecs"),Ts=require("@aws-sdk/client-s3"),Se=require("@aws-sdk/client-ssm"),It=require("@aws-sdk/client-sts"),Os=require("@medplum/core"),xs=N(require("node-fetch"),1),$s=require("node:fs"),Ns=N(vr(),1);var vs=N(require("node:readline"),1),wt;function Et(){wt=vs.default.createInterface({input:process.stdin,output:process.stdout})}function St(){wt.close()}function c(e){wt.write(e+`
|
|
5
5
|
`)}function v(e){c(`
|
|
6
6
|
`+e+`
|
|
7
|
-
`)}function L(e,t=""){return new Promise(r=>{wt.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function Rt(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await L(o)||r;if(t.includes(n))return n;c("Please choose one of the following options: "+t.join(", "))}}async function Ee(e,t,r){return parseInt(await Rt(e,t.map(o=>o.toString()),r.toString()),10)}async function re(e){return(await Rt(e,["y","n"])).toLowerCase()==="y"}async function Ke(e){if(!await re(e))throw c("Exiting..."),new Error("User cancelled")}var At=new Q.CloudFormationClient({}),Su=new Pt.CloudFrontClient({region:"us-east-1"}),_m=new Cs.ECSClient({}),qe=new Ts.S3Client({}),Ru="medplum:environment";async function br(){let e=[],t=(0,Q.paginateListStacks)({client:At},{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 Re(e){let t=await br();for(let r of t){let o=r.StackName,n=await Cr(o);if(n?.tag===e)return n}}async function Cr(e){let t={};if(await bs(At,e,t),await At.config.region()!=="us-east-1")try{await bs(new Q.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function bs(e,t,r){let o=new Q.DescribeStacksCommand({StackName:t}),s=(await e.send(o))?.Stacks?.[0],i=s?.Tags?.find(l=>l.Key===Ru);if(!i)return;let a=await e.send(new Q.DescribeStackResourcesCommand({StackName:t}));if(a.StackResources){e===At&&(r.stack=s,r.tag=i.Value);for(let l of a.StackResources)Au(l,r)}}function Au(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 vt(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: ${Pu(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 Pu(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function bt(e){let t=await Su.send(new Pt.CreateInvalidationCommand({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function Ct(e){let o=(await(await(0,xs.default)("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)=>Ns.compare(s,n)),e?o.slice(0,o.indexOf(e)):o}async function Tt(e,t,r){let o=new Se.SSMClient({region:e});for(let[n,s]of Object.entries(r)){let i=t+n,a=s.toString(),l=await Iu(o,i);l!==void 0&&l!==a&&(c(`Parameter "${i}" exists with different value.`),await Ke(`Do you want to overwrite "${i}"?`)),await vu(o,i,a)}}async function Iu(e,t){let r=new Se.GetParameterCommand({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function vu(e,t,r){let o=new Se.PutParameterCommand({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}function oe(e,t){if(console.log(`Config not found: ${e} (${j(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=(0,$s.readdirSync)(".",{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 It.STSClient,r=new It.GetCallerIdentityCommand({}),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",(0,Os.normalizeErrorString)(t))}}async function Ls(e){let t=await Re(e);if(!t)throw await Ae(e),new Error(`Stack not found: ${e}`);vt(t)}var de=require("@aws-sdk/client-acm"),Ot=require("@aws-sdk/client-cloudfront"),xt=require("@aws-sdk/client-sts"),Ds=require("@medplum/core"),He=require("node:crypto"),Ms=require("node:fs");var bu=e=>`${e}DomainName`,_s=e=>`${e}SslCertArn`;async function Us(){let e={apiPort:8103,region:"us-east-1"};Et(),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 Cu(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 Ke("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 L("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 L("What is the config file name?",`medplum.${e.name}.config.json`);(0,Ms.existsSync)(r)&&(c("Config file already exists."),await Ke("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 L("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 L("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 L("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 L("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 L("Enter your support email address:");v("API DOMAIN NAME"),c("Medplum deploys a REST API for the backend services."),e.apiDomainName=await L("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 L("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 L("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 L("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 Ee("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 re("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 Ee("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 Ee("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 Ee("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 Ee("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 Ct())[0]??"latest";e.serverImage=await L("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 $u(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 Tu(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 Ou(e,a,u,h);e[_s(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 re("Do you want to store these values in AWS Parameter Store?"))await Tt(e.region,`/medplum/${e.name}/`,l);else{let u=j(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(""),St()}async function Cu(e){try{let t=new xt.STSClient({region:e}),r=new xt.GetCallerIdentityCommand({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Tu(e){let t=await ks(e);if(e!=="us-east-1"){let r=await ks("us-east-1");t.push(...r)}return t}async function ks(e){try{let t=new de.ACMClient({region:e}),r=new de.ListCertificatesCommand({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Ou(e,t,r,o){let n=e[bu(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 re("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${_s(o)}" setting.`),"TODO";let i=await xu(r,n);return c("Certificate ARN: "+i),i}async function xu(e,t){try{let r=await Rt("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new de.ACMClient({region:e}),n=new de.RequestCertificateCommand({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 $u(e,t){let r=(0,He.randomUUID)(),o=(0,He.generateKeyPairSync)("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new Ot.CloudFrontClient({region:e}).send(new Ot.CreatePublicKeyCommand({PublicKeyConfig:{Name:t,CallerReference:(0,He.randomUUID)(),EncodedKey:o.publicKey}}))).PublicKey?.Id,publicKey:o.publicKey,privateKey:o.privateKey,passphrase:r}}catch(n){console.log("Error: Unable to create signing key: ",(0,Ds.normalizeErrorString)(n));return}}async function js(){let e=await br();for(let t of e){let r=t.StackName,o=await Cr(r);o&&(vt(o),console.log(""))}}var Fs=require("@aws-sdk/client-s3"),B=require("@medplum/core"),Bs=N(require("fast-glob"),1),Tr=N(require("node-fetch"),1),_=require("node:fs"),Ws=require("node:os"),me=require("node:path"),Ks=require("node:stream/promises");async function qs(e,t){let r=q(e,t);if(!r)throw oe(e,t),new Error(`Config not found: ${e}`);let o=await Re(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 Lu("@medplum/app",i)}Hs(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 Du(s,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await bt(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Nu(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await(0,Tr.default)(r)).json()}async function Lu(e,t){let o=(await Nu(e,t)).dist.tarball,n=(0,_.mkdtempSync)((0,me.join)((0,Ws.tmpdir)(),"tarball-"));try{let s=await(0,Tr.default)(o),i=So(n);return await(0,Ks.pipeline)(s.body,i),(0,me.join)(n,"package","dist")}catch(s){throw(0,_.rmSync)(n,{recursive:!0,force:!0}),s}}function Hs(e,t){for(let r of(0,_.readdirSync)(e,{withFileTypes:!0})){let o=(0,me.join)(e,r.name);r.isDirectory()?Hs(o,t):r.isFile()&&o.endsWith(".js")&&ku(o,t)}}function ku(e,t){let r=(0,_.readFileSync)(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);(0,_.writeFileSync)(e,r)}async function Du(e,t,r){let o=[["assets/**/*.css",B.ContentType.CSS,!0],["assets/**/*.css.map",B.ContentType.JSON,!0],["assets/**/*.js",B.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",B.ContentType.JSON,!0],["assets/**/*.txt",B.ContentType.TEXT,!0],["assets/**/*.ico",B.ContentType.FAVICON,!0],["img/**/*.png",B.ContentType.PNG,!0],["img/**/*.svg",B.ContentType.SVG,!0],["robots.txt",B.ContentType.TEXT,!0],["index.html",B.ContentType.HTML,!1]];for(let n of o)await Mu({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function Mu(e){let t=Bs.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await _u((0,me.join)(e.rootDir,r),e)}async function _u(e,t){let r=(0,_.createReadStream)(e),o=e.substring(t.rootDir.length+1).split(me.sep).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 qe.send(new Fs.PutObjectCommand(n))}var $t=require("@aws-sdk/client-s3");async function Vs(e,t){if(!q(e,t))throw oe(e,t),new Error(`Config not found: ${e}`);let o=await Re(e);if(!o)throw await Ae(e),new Error(`Stack not found: ${e}`);await Gs("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await Gs("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function Gs(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 Uu(s);if(Fu(a,s,i))throw new Error(`${e} bucket already has policy statement`);Bu(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 ju(s,a),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await bt(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Uu(e){let t=await qe.send(new $t.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function ju(e,t){await qe.send(new $t.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function Fu(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 Bu(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 Js(e,t){try{Et();let r=q(e,t);if(!r)throw oe(e,t),new Error(`Config not found: ${e}`);let o=Eo(e)??{};if(!t.yes&&Object.keys(o).length===0){let n=j(e,{server:!0});if(console.log(ue.yellow(`Config file ${n} not found!`)),!await re("Do you want to proceed?")){console.log(ue.red(`Run Aborted, please ensure ${n} is present and try again.`));return}}Wu(r,o),qu(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(ue.yellow("Dry run - skipping updates!")):(t.yes||await re("Do you want to store these values in AWS Parameter Store?"))&&await Tt(r.region,`/medplum/${r.name}/`,o)}finally{St()}}function Wu(e,t){Nt(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),Nt(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),Nt(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),Nt(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function Nt(e,t,r){if(Ku(e,t))throw new Error(r)}function Ku(e,t){return e!==void 0&&t!==void 0&&e!==t}function qu(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 zs=require("node:child_process"),Pe=N(vr(),1);async function Ys(e,t){let r=await R(t),o=q(e,t);if(!o)throw console.log(`Configuration file ${j(e)} not found`),oe(e,t),new Error(`Config not found: ${e}`);let n=o.serverImage.lastIndexOf(":"),s=o.serverImage.slice(0,n),i=await Hu(r,o),a=await Xs(i);for(;a;){if(t.toVersion&&Pe.gt(a,t.toVersion)){console.log(`Skipping update to v${a}`);break}console.log(`Performing update to v${a}`),o.serverImage=`${s}:${a}`,Gu(e,o),await r.startAsyncRequest("/admin/super/migrate"),a=await Xs(a)}}async function Hu(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 Xs(e,t){let r=await Ct(e),o=r[0];return r.filter(n=>n===o||n===t||Pe.gte(n,Pe.inc(e,"minor"))).pop()}function Gu(e,t){let r=j(e);C(r,t);let o=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+o);let n=(0,zs.spawnSync)(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 Qs(){let e=new g("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(Us),e.command("list").description("List Medplum AWS CloudFormation stacks").action(js),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(Ls),e.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(sr(`Update the AWS Parameter Store config values.
|
|
7
|
+
`)}function L(e,t=""){return new Promise(r=>{wt.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function Rt(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await L(o)||r;if(t.includes(n))return n;c("Please choose one of the following options: "+t.join(", "))}}async function Ee(e,t,r){return Number.parseInt(await Rt(e,t.map(o=>o.toString()),r.toString()),10)}async function re(e){return(await Rt(e,["y","n"])).toLowerCase()==="y"}async function Ke(e){if(!await re(e))throw c("Exiting..."),new Error("User cancelled")}var At=new Q.CloudFormationClient({}),Su=new Pt.CloudFrontClient({region:"us-east-1"}),_m=new Cs.ECSClient({}),qe=new Ts.S3Client({}),Ru="medplum:environment";async function br(){let e=[],t=(0,Q.paginateListStacks)({client:At},{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 Re(e){let t=await br();for(let r of t){let o=r.StackName,n=await Cr(o);if(n?.tag===e)return n}}async function Cr(e){let t={};if(await bs(At,e,t),await At.config.region()!=="us-east-1")try{await bs(new Q.CloudFormationClient({region:"us-east-1"}),e+"-us-east-1",t)}catch{}return t}async function bs(e,t,r){let o=new Q.DescribeStacksCommand({StackName:t}),s=(await e.send(o))?.Stacks?.[0],i=s?.Tags?.find(l=>l.Key===Ru);if(!i)return;let a=await e.send(new Q.DescribeStackResourcesCommand({StackName:t}));if(a.StackResources){e===At&&(r.stack=s,r.tag=i.Value);for(let l of a.StackResources)Au(l,r)}}function Au(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 vt(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: ${Pu(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 Pu(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function bt(e){let t=await Su.send(new Pt.CreateInvalidationCommand({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function Ct(e){let o=(await(await(0,xs.default)("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)=>Ns.compare(s,n)),e?o.slice(0,o.indexOf(e)):o}async function Tt(e,t,r){let o=new Se.SSMClient({region:e});for(let[n,s]of Object.entries(r)){let i=t+n,a=s.toString(),l=await Iu(o,i);l!==void 0&&l!==a&&(c(`Parameter "${i}" exists with different value.`),await Ke(`Do you want to overwrite "${i}"?`)),await vu(o,i,a)}}async function Iu(e,t){let r=new Se.GetParameterCommand({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function vu(e,t,r){let o=new Se.PutParameterCommand({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}function oe(e,t){if(console.log(`Config not found: ${e} (${j(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=(0,$s.readdirSync)(".",{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 It.STSClient,r=new It.GetCallerIdentityCommand({}),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",(0,Os.normalizeErrorString)(t))}}async function Ls(e){let t=await Re(e);if(!t)throw await Ae(e),new Error(`Stack not found: ${e}`);vt(t)}var de=require("@aws-sdk/client-acm"),Ot=require("@aws-sdk/client-cloudfront"),xt=require("@aws-sdk/client-sts"),Ds=require("@medplum/core"),He=require("node:crypto"),Ms=require("node:fs");var bu=e=>`${e}DomainName`,_s=e=>`${e}SslCertArn`;async function Us(){let e={apiPort:8103,region:"us-east-1"};Et(),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 Cu(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 Ke("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 L("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 L("What is the config file name?",`medplum.${e.name}.config.json`);(0,Ms.existsSync)(r)&&(c("Config file already exists."),await Ke("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 L("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 L("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 L("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 L("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 L("Enter your support email address:");v("API DOMAIN NAME"),c("Medplum deploys a REST API for the backend services."),e.apiDomainName=await L("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 L("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 L("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 L("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 Ee("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 re("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 Ee("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 Ee("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 Ee("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 Ee("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 Ct())[0]??"latest";e.serverImage=await L("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 $u(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 Tu(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 Ou(e,a,u,h);e[_s(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 re("Do you want to store these values in AWS Parameter Store?"))await Tt(e.region,`/medplum/${e.name}/`,l);else{let u=j(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(""),St()}async function Cu(e){try{let t=new xt.STSClient({region:e}),r=new xt.GetCallerIdentityCommand({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Tu(e){let t=await ks(e);if(e!=="us-east-1"){let r=await ks("us-east-1");t.push(...r)}return t}async function ks(e){try{let t=new de.ACMClient({region:e}),r=new de.ListCertificatesCommand({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Ou(e,t,r,o){let n=e[bu(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 re("Do you want to request a new certificate?"))return c(`Please add your certificate ARN to the config file in the "${_s(o)}" setting.`),"TODO";let i=await xu(r,n);return c("Certificate ARN: "+i),i}async function xu(e,t){try{let r=await Rt("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new de.ACMClient({region:e}),n=new de.RequestCertificateCommand({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 $u(e,t){let r=(0,He.randomUUID)(),o=(0,He.generateKeyPairSync)("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:r}});try{return{keyId:(await new Ot.CloudFrontClient({region:e}).send(new Ot.CreatePublicKeyCommand({PublicKeyConfig:{Name:t,CallerReference:(0,He.randomUUID)(),EncodedKey:o.publicKey}}))).PublicKey?.Id,publicKey:o.publicKey,privateKey:o.privateKey,passphrase:r}}catch(n){console.log("Error: Unable to create signing key: ",(0,Ds.normalizeErrorString)(n));return}}async function js(){let e=await br();for(let t of e){let r=t.StackName,o=await Cr(r);o&&(vt(o),console.log(""))}}var Fs=require("@aws-sdk/client-s3"),B=require("@medplum/core"),Bs=N(require("fast-glob"),1),Tr=N(require("node-fetch"),1),_=require("node:fs"),Ws=require("node:os"),me=require("node:path"),Ks=require("node:stream/promises");async function qs(e,t){let r=q(e,t);if(!r)throw oe(e,t),new Error(`Config not found: ${e}`);let o=await Re(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 Lu("@medplum/app",i)}Hs(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 Du(s,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await bt(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Nu(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await(0,Tr.default)(r)).json()}async function Lu(e,t){let o=(await Nu(e,t)).dist.tarball,n=(0,_.mkdtempSync)((0,me.join)((0,Ws.tmpdir)(),"tarball-"));try{let s=await(0,Tr.default)(o),i=So(n);return await(0,Ks.pipeline)(s.body,i),(0,me.join)(n,"package","dist")}catch(s){throw(0,_.rmSync)(n,{recursive:!0,force:!0}),s}}function Hs(e,t){for(let r of(0,_.readdirSync)(e,{withFileTypes:!0})){let o=(0,me.join)(e,r.name);r.isDirectory()?Hs(o,t):r.isFile()&&o.endsWith(".js")&&ku(o,t)}}function ku(e,t){let r=(0,_.readFileSync)(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);(0,_.writeFileSync)(e,r)}async function Du(e,t,r){let o=[["assets/**/*.css",B.ContentType.CSS,!0],["assets/**/*.css.map",B.ContentType.JSON,!0],["assets/**/*.js",B.ContentType.JAVASCRIPT,!0],["assets/**/*.js.map",B.ContentType.JSON,!0],["assets/**/*.txt",B.ContentType.TEXT,!0],["assets/**/*.ico",B.ContentType.FAVICON,!0],["img/**/*.png",B.ContentType.PNG,!0],["img/**/*.svg",B.ContentType.SVG,!0],["robots.txt",B.ContentType.TEXT,!0],["index.html",B.ContentType.HTML,!1]];for(let n of o)await Mu({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function Mu(e){let t=Bs.default.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await _u((0,me.join)(e.rootDir,r),e)}async function _u(e,t){let r=(0,_.createReadStream)(e),o=e.substring(t.rootDir.length+1).split(me.sep).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 qe.send(new Fs.PutObjectCommand(n))}var $t=require("@aws-sdk/client-s3");async function Vs(e,t){if(!q(e,t))throw oe(e,t),new Error(`Config not found: ${e}`);let o=await Re(e);if(!o)throw await Ae(e),new Error(`Stack not found: ${e}`);await Gs("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await Gs("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function Gs(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 Uu(s);if(Fu(a,s,i))throw new Error(`${e} bucket already has policy statement`);Bu(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 ju(s,a),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await bt(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function Uu(e){let t=await qe.send(new $t.GetBucketPolicyCommand({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function ju(e,t){await qe.send(new $t.PutBucketPolicyCommand({Bucket:e,Policy:JSON.stringify(t)}))}function Fu(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 Bu(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 Js(e,t){try{Et();let r=q(e,t);if(!r)throw oe(e,t),new Error(`Config not found: ${e}`);let o=Eo(e)??{};if(!t.yes&&Object.keys(o).length===0){let n=j(e,{server:!0});if(console.log(ue.yellow(`Config file ${n} not found!`)),!await re("Do you want to proceed?")){console.log(ue.red(`Run Aborted, please ensure ${n} is present and try again.`));return}}Wu(r,o),qu(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(ue.yellow("Dry run - skipping updates!")):(t.yes||await re("Do you want to store these values in AWS Parameter Store?"))&&await Tt(r.region,`/medplum/${r.name}/`,o)}finally{St()}}function Wu(e,t){Nt(e.apiPort,t.port,`Infra "apiPort" (${e.apiPort}) does not match server "port" (${t.port})`),Nt(e.baseUrl,t.baseUrl,`Infra "baseUrl" (${e.baseUrl}) does not match server "baseUrl" (${t.baseUrl})`),Nt(e.appDomainName&&`https://${e.appDomainName}/`,t.appBaseUrl,`Infra "appDomainName" (${e.appDomainName}) does not match server "appBaseUrl" (${t.appBaseUrl})`),Nt(e.storageDomainName&&`https://${e.storageDomainName}/binary/`,t.storageBaseUrl,`Infra "storageDomainName" (${e.storageDomainName}) does not match server "storageBaseUrl" (${t.storageBaseUrl})`)}function Nt(e,t,r){if(Ku(e,t))throw new Error(r)}function Ku(e,t){return e!==void 0&&t!==void 0&&e!==t}function qu(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 zs=require("node:child_process"),Pe=N(vr(),1);async function Ys(e,t){let r=await R(t),o=q(e,t);if(!o)throw console.log(`Configuration file ${j(e)} not found`),oe(e,t),new Error(`Config not found: ${e}`);let n=o.serverImage.lastIndexOf(":"),s=o.serverImage.slice(0,n),i=await Hu(r,o),a=await Xs(i);for(;a;){if(t.toVersion&&Pe.gt(a,t.toVersion)){console.log(`Skipping update to v${a}`);break}console.log(`Performing update to v${a}`),o.serverImage=`${s}:${a}`,Gu(e,o),await r.startAsyncRequest("/admin/super/migrate"),a=await Xs(a)}}async function Hu(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 Xs(e,t){let r=await Ct(e),o=r[0];return r.filter(n=>n===o||n===t||Pe.gte(n,Pe.inc(e,"minor"))).pop()}function Gu(e,t){let r=j(e);C(r,t);let o=`npx cdk deploy -c config=${r}${t.region!=="us-east-1"?" --all":""}`;console.log("> "+o);let n=(0,zs.spawnSync)(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 Qs(){let e=new g("aws").description("Commands to manage AWS resources");return e.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(Us),e.command("list").description("List Medplum AWS CloudFormation stacks").action(js),e.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>","The Medplum stack tag").action(Ls),e.command("update-config").alias("deploy-config").summary("Update the AWS Parameter Store config values.").description(sr(`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
|
|