@medplum/cli 2.1.0 → 2.1.2
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 +4 -4
- package/dist/cjs/index.cjs.map +4 -4
- package/dist/esm/index.mjs +4 -4
- package/dist/esm/index.mjs.map +4 -4
- package/dist/types/aws/update-bucket-policies.d.ts +14 -0
- package/dist/types/aws/utils.d.ts +12 -0
- package/dist/types/rest.d.ts +2 -1
- package/dist/types/util/client.d.ts +3 -1
- package/dist/types/utils.d.ts +9 -9
- package/package.json +13 -13
package/dist/esm/index.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var ot=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import{MEDPLUM_VERSION as _i,normalizeErrorString as Ki}from"@medplum/core";import{Command as Ti}from"commander";import Ii from"dotenv";import{ContentType as Ne,getDisplayString as Qo,normalizeErrorString as en}from"@medplum/core";import{exec as tn}from"child_process";import{createServer as rn}from"http";import{platform as on}from"os";import{ClientStorage as fr}from"@medplum/core";import{existsSync as nt,mkdirSync as hr,readFileSync as yr,writeFileSync as gr}from"fs";import{homedir as wr}from"os";import{resolve as it}from"path";var E=class extends fr{constructor(r){super();this.dirName=it(wr(),".medplum"),this.fileName=it(this.dirName,r+".json")}clear(){this.writeFile({})}getString(r){return this.readFile()?.[r]}setString(r,o){let n=this.readFile()??{};o?n[r]=o:delete n[r],this.writeFile(n)}getObject(r){let o=this.getString(r);return o?JSON.parse(o):void 0}setObject(r,o){this.setString(r,o?JSON.stringify(o):void 0)}readFile(){if(nt(this.fileName))return JSON.parse(yr(this.fileName,"utf8"))}writeFile(r){nt(this.dirName)||hr(this.dirName),gr(this.fileName,JSON.stringify(r,null,2),"utf8")}};import{MedplumClient as Sr}from"@medplum/core";async function u(e){let t=e.profile??"default",r=new E(t),o=r.getObject("options");if(t!=="default"&&!o)throw new Error(`Profile "${t}" does not exist`);let{baseUrl:n,fhirUrlPath:a,accessToken:s,tokenUrl:c,authorizeUrl:p,clientId:f,clientSecret:y}=Er(e,r),T=e.fetch??fetch,I=new Sr({fetch:T,baseUrl:n,tokenUrl:c,fhirUrlPath:a,authorizeUrl:p,storage:r,onUnauthenticated:br});return s&&I.setAccessToken(s),o?.authType==="client_credentials"?(I.setBasicAuth(f,y),await I.startClientLogin(f,y)):o?.authType==="basic"&&I.setBasicAuth(f,y),I}function Er(e,t){let r=t.getObject("options"),o=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",n=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,a=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,s=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,c=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,p=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,f=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:n,accessToken:a,tokenUrl:s,authorizeUrl:c,clientId:p,clientSecret:f}}function br(){console.log("Unauthenticated: run `npx medplum login` to sign in")}import{Command as Cr,Option as vr}from"commander";function m(e){return new Cr(e).option("--client-id <clientId>","FHIR server client id").option("--client-secret <clientSecret>","FHIR server client secret").option("--base-url <baseUrl>","FHIR server base url").option("--token-url <tokenUrl>","FHIR server token url").option("--authorize-url <authorizeUrl>","FHIR server authorize url").option("--fhir-url-path <fhirUrlPath>","FHIR server url path").option("--scope <scope>","JWT scope").option("--access-token <accessToken>","Access token for token exchange authentication").option("--callback-url <callbackUrl>","Callback URL for authorization code flow").option("--subject <subject>","Subject for JWT authentication").option("--audience <audience>","Audience for JWT authentication").option("--issuer, <issuer>","Issuer for JWT authentication").option("--private-key-path <privateKeyPath>","Private key path for JWT assertion").option("--audience <audience>","Audience for JWT assertion").option("-p, --profile <profile>","Profile name").addOption(new vr("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"]))}import{ContentType as We,encodeBase64 as At}from"@medplum/core";import{createHmac as No,createPrivateKey as Uo,randomBytes as Lo}from"crypto";import{existsSync as $o,readFileSync as xt,writeFile as Bo}from"fs";import{Buffer as be}from"buffer";var A=new TextEncoder,b=new TextDecoder,ji=2**32;function H(...e){let t=e.reduce((n,{length:a})=>n+a,0),r=new Uint8Array(t),o=0;return e.forEach(n=>{r.set(n,o),o+=n.length}),r}var w;be.isEncoding("base64url")?w=e=>be.from(e).toString("base64url"):w=e=>be.from(e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var U=class extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(t){var r;super(t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}};var d=class extends U{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var x=class extends U{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}},R=class extends U{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}};import{KeyObject as Pr}from"crypto";import*as ve from"util";var P=ve.types.isKeyObject?e=>ve.types.isKeyObject(e):e=>e!=null&&e instanceof Pr;import*as st from"crypto";import*as Ae from"util";var _r=st.webcrypto,oe=_r,C=Ae.types.isCryptoKey?e=>Ae.types.isCryptoKey(e):e=>!1;function O(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function ne(e,t){return e.name===t}function xe(e){return parseInt(e.name.slice(4),10)}function Kr(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Tr(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let o=t.pop();r+=`one of ${t.join(", ")}, or ${o}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function ct(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!ne(e.algorithm,"HMAC"))throw O("HMAC");let o=parseInt(t.slice(2),10);if(xe(e.algorithm.hash)!==o)throw O(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ne(e.algorithm,"RSASSA-PKCS1-v1_5"))throw O("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(xe(e.algorithm.hash)!==o)throw O(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ne(e.algorithm,"RSA-PSS"))throw O("RSA-PSS");let o=parseInt(t.slice(2),10);if(xe(e.algorithm.hash)!==o)throw O(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw O("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!ne(e.algorithm,"ECDSA"))throw O("ECDSA");let o=Kr(t);if(e.algorithm.namedCurve!==o)throw O(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Tr(e,r)}function dt(e,t,...r){if(r.length>2){let o=r.pop();e+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor&&t.constructor.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var _=(e,...t)=>dt("Key must be ",e,...t);function Pe(e,t,...r){return dt(`Key for the ${e} algorithm must be `,t,...r)}var _e=e=>P(e)||C(e),l=["KeyObject"];(globalThis.CryptoKey||!(oe===null||oe===void 0)&&oe.CryptoKey)&&l.push("CryptoKey");import{promisify as mt}from"util";import{inflateRaw as Wr,deflateRaw as Rr}from"zlib";var Da=mt(Wr),Ja=mt(Rr);var Mr=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let o of t){let n=Object.keys(o);if(!r||r.size===0){r=new Set(n);continue}for(let a of n){if(r.has(a))return!1;r.add(a)}}return!0},L=Mr;function Dr(e){return typeof e=="object"&&e!==null}function S(e){if(!Dr(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}import{diffieHellman as ds,generateKeyPair as Gr,KeyObject as ps}from"crypto";import{promisify as zr}from"util";import{Buffer as ie}from"buffer";import{createPublicKey as Jr,KeyObject as Nr}from"crypto";var Ur=ie.from([42,134,72,206,61,3,1,7]),Lr=ie.from([43,129,4,0,34]),$r=ie.from([43,129,4,0,35]),Br=ie.from([43,129,4,0,10]),Ke=new WeakMap,Fr=e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new d("Unsupported key curve for this operation")}},ut=(e,t)=>{var r;let o;if(C(e))o=Nr.from(e);else if(P(e))o=e;else throw new TypeError(_(e,...l));if(o.type==="secret")throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(o.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${o.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${o.asymmetricKeyType.slice(1)}`;case"ec":{if(Ke.has(o))return Ke.get(o);let n=(r=o.asymmetricKeyDetails)===null||r===void 0?void 0:r.namedCurve;if(!n&&o.type==="private")n=ut(Jr(o),!0);else if(!n){let s=o.export({format:"der",type:"spki"}),c=s[1]<128?14:15,p=s[c],f=s.slice(c+1,c+1+p);if(f.equals(Ur))n="prime256v1";else if(f.equals(Lr))n="secp384r1";else if(f.equals($r))n="secp521r1";else if(f.equals(Br))n="secp256k1";else throw new d("Unsupported key curve for this operation")}if(t)return n;let a=Fr(n);return Ke.set(o,a),a}default:throw new TypeError("Invalid asymmetric key type for this operation")}};var ae=ut;var Es=zr(Gr);import{promisify as qr}from"util";import{KeyObject as _s,pbkdf2 as Xr}from"crypto";var Js=qr(Xr);var Te=new WeakMap,se=(e,t)=>{let r=e.readUInt8(1);if(!(r&128))return t===0?r:se(e.subarray(2+r),t-1);let o=r&127;r=0;for(let n=0;n<o;n++){r<<=8;let a=e.readUInt8(2+n);r|=a}return t===0?r:se(e.subarray(2+r),t-1)},Yr=(e,t)=>{let r=e.readUInt8(1);if(!(r&128))return se(e.subarray(2),t);let o=r&127;return se(e.subarray(2+o),t)},Zr=e=>{var t,r;if(Te.has(e))return Te.get(e);let o=(r=(t=e.asymmetricKeyDetails)===null||t===void 0?void 0:t.modulusLength)!==null&&r!==void 0?r:Yr(e.export({format:"der",type:"pkcs1"}),e.type==="private"?1:0)-1<<3;return Te.set(e,o),o};var q=(e,t)=>{if(Zr(e)<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)};import{Buffer as v}from"buffer";var Qr=2,eo=3,to=4,ro=48,nc=v.from([0]),ic=v.from([Qr]),ac=v.from([eo]),sc=v.from([ro]),cc=v.from([to]);var dc=new Map([["P-256",v.from("06 08 2A 86 48 CE 3D 03 01 07".replace(/ /g,""),"hex")],["secp256k1",v.from("06 05 2B 81 04 00 0A".replace(/ /g,""),"hex")],["P-384",v.from("06 05 2B 81 04 00 22".replace(/ /g,""),"hex")],["P-521",v.from("06 05 2B 81 04 00 23".replace(/ /g,""),"hex")],["ecPublicKey",v.from("06 07 2A 86 48 CE 3D 02 01".replace(/ /g,""),"hex")],["X25519",v.from("06 03 2B 65 6E".replace(/ /g,""),"hex")],["X448",v.from("06 03 2B 65 6F".replace(/ /g,""),"hex")],["Ed25519",v.from("06 03 2B 65 70".replace(/ /g,""),"hex")],["Ed448",v.from("06 03 2B 65 71".replace(/ /g,""),"hex")]]);var[D,ce]=process.versions.node.split(".").map(e=>parseInt(e,10)),ft=D>=16||D===15&&ce>=13,J=!("electron"in process.versions)&&(D>=17||D===16&&ce>=9),oo=D>=16||D===15&&ce>=9,no=D>=16||D===15&&ce>=12;var ao=(e,t)=>{if(!(t instanceof Uint8Array)){if(!_e(t))throw new TypeError(Pe(e,t,...l,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${l.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},so=(e,t,r)=>{if(!_e(t))throw new TypeError(Pe(e,t,...l));if(t.type==="secret")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${l.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},co=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?ao(e,t):so(e,t,r)},X=co;function yo(e,t,r,o,n){if(n.crit!==void 0&&o.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return new Set;if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a;r!==void 0?a=new Map([...Object.entries(r),...t.entries()]):a=t;for(let s of o.crit){if(!a.has(s))throw new d(`Extension Header Parameter "${s}" is not recognized`);if(n[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(a.get(s)&&o[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(o.crit)}var B=yo;var bo=Symbol();import*as Y from"crypto";import{promisify as Po}from"util";function de(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"EdDSA":return;default:throw new d(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import{constants as wt}from"crypto";var St={padding:wt.RSA_PKCS1_PSS_PADDING,saltLength:wt.RSA_PSS_SALTLEN_DIGEST},Co=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function pe(e,t){switch(e){case"EdDSA":if(!["ed25519","ed448"].includes(t.asymmetricKeyType))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");return t;case"RS256":case"RS384":case"RS512":if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");return q(t,e),t;case(J&&"PS256"):case(J&&"PS384"):case(J&&"PS512"):if(t.asymmetricKeyType==="rsa-pss"){let{hashAlgorithm:r,mgf1HashAlgorithm:o,saltLength:n}=t.asymmetricKeyDetails,a=parseInt(e.slice(-3),10);if(r!==void 0&&(r!==`sha${a}`||o!==r))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(n!==void 0&&n>a>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");return q(t,e),{key:t,...St};case(!J&&"PS256"):case(!J&&"PS384"):case(!J&&"PS512"):if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");return q(t,e),{key:t,...St};case"ES256":case"ES256K":case"ES384":case"ES512":{if(t.asymmetricKeyType!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let r=ae(t),o=Co.get(e);if(r!==o)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${o}, got ${r}`);return{dsaEncoding:"ieee-p1363",key:t}}default:throw new d(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import*as F from"crypto";import{promisify as Ao}from"util";function He(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new d(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import{KeyObject as Et,createSecretKey as vo}from"crypto";function me(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(_(t,...l));return vo(t)}if(t instanceof Et)return t;if(C(t))return ct(t,e,r),Et.from(t);throw new TypeError(_(t,...l,"Uint8Array"))}var ke;F.sign.length>3?ke=Ao(F.sign):ke=F.sign;var xo=async(e,t,r)=>{let o=me(e,t,"sign");if(e.startsWith("HS")){let n=F.createHmac(He(e),o);return n.update(r),n.digest()}return ke(de(e),r,pe(e,o))},Oe=xo;var bt;Y.verify.length>4&&ft?bt=Po(Y.verify):bt=Y.verify;var Z=e=>Math.floor(e.getTime()/1e3);var Ko=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,ue=e=>{let t=Ko.exec(e);if(!t)throw new TypeError("Invalid time period format");let r=parseFloat(t[1]);switch(t[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(r);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(r*60);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(r*3600);case"day":case"days":case"d":return Math.round(r*86400);case"week":case"weeks":case"w":return Math.round(r*604800);default:return Math.round(r*31557600)}};var G=class{constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new x("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!L(this._protectedHeader,this._unprotectedHeader))throw new x("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=B(x,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),a=!0;if(n.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new x('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=o;if(typeof s!="string"||!s)throw new x('JWS "alg" (Algorithm) Header Parameter missing or invalid');X(s,t,"sign");let c=this._payload;a&&(c=A.encode(w(c)));let p;this._protectedHeader?p=A.encode(w(JSON.stringify(this._protectedHeader))):p=A.encode("");let f=H(p,A.encode("."),c),y=await Oe(s,t,f),T={signature:w(y),payload:""};return a&&(T.payload=b.decode(c)),this._unprotectedHeader&&(T.header=this._unprotectedHeader),this._protectedHeader&&(T.protected=b.decode(p)),T}};var Q=class{constructor(t){this._flattened=new G(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let o=await this._flattened.sign(t,r);if(o.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${o.protected}.${o.payload}.${o.signature}`}};var z=class{constructor(t){if(!S(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:t}:this._payload={...this._payload,nbf:Z(new Date)+ue(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:t}:this._payload={...this._payload,exp:Z(new Date)+ue(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:Z(new Date)}:this._payload={...this._payload,iat:t},this}};var ee=class extends z{setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){var o;let n=new Q(A.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray((o=this._protectedHeader)===null||o===void 0?void 0:o.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new R("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};import{createSecretKey as sl,generateKeyPair as Do}from"crypto";import{promisify as Jo}from"util";var ul=Jo(Do);import{homedir as Fo}from"os";import{basename as Go,extname as zo,join as jo,resolve as Vo}from"path";import qo from"tar";function W(e){console.log(JSON.stringify(e,null,2))}async function Re(e,t,r){let o=t.source,n=De(o);if(n)try{console.log("Saving source code...");let a=await e.createAttachment(n,Go(o),Zo(o));console.log("Updating bot.....");let s=await e.updateResource({...r,sourceCode:a});console.log("Success! New bot version: "+s.meta?.versionId)}catch(a){console.log("Update error: ",a)}}async function Pt(e,t,r){let o=t.dist??t.source,n=De(o);if(n)try{console.log("Deploying bot...");let a=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n});console.log("Deploy result: "+a.issue?.[0]?.details?.text)}catch(a){console.log("Deploy error: ",a)}}async function Me(e,t){if(t.length<4){console.log("Error: command needs to be npx medplum <new-bot-name> <project-id> <source-file> <dist-file>");return}let r=t[0],o=t[1],n=t[2],a=t[3];try{let s={name:r,description:""},c=await e.post("admin/projects/"+o+"/bot",s),p=await e.readResource("Bot",c.id),f={name:r,id:c.id,source:n,dist:a};await Re(e,f,p),console.log(`Success! Bot created: ${p.id}`),Xo(f)}catch(s){console.log("Error while creating new bot: "+s)}}function _t(e){let t=new RegExp("^"+Yo(e).replace(/\\\*/g,".*")+"$"),r=le()?.bots?.filter(o=>t.test(o.name));return r||[]}function le(e){let t=e?`medplum.${e}.config.json`:"medplum.config.json",r=De(t);if(r)return JSON.parse(r)}function De(e){let t=Vo(process.cwd(),e);return $o(t)?xt(t,"utf8"):(console.log("Error: File does not exist: "+t),"")}function Xo(e){let t=le();t?.bots?.push(e),Bo("medplum.config.json",JSON.stringify(t),()=>{console.log(`Bot added to config: ${e.id}`)})}function Yo(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Kt(e){let o=0,n=0;return qo.x({cwd:e,filter:(a,s)=>{if(o++,o>100)throw new Error("Tar extractor reached max number of files");if(n+=s.size,n>10485760)throw new Error("Tar extractor reached max size");return!0}})}function Je(){return{extension:[{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}]}}function Zo(e){let t=zo(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?We.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?We.TYPESCRIPT:We.TEXT}function fe(e,t){let r=new E(e),o={name:e,...t};r.setObject("options",o),console.log(`${e} profile created`)}function he(e){return new E(e).getObject("options")}function Tt(e,t){return t==="default"?!0:!!e.getObject("options")}async function It(e,t){let r={typ:"JWT",alg:"HS256"},o=Math.floor(Date.now()/1e3),n={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:o,iat:o,exp:o+604800},a=At(JSON.stringify(r)),s=At(JSON.stringify(n)),c=`${a}.${s}`,p=No("sha256",t.clientSecret).update(c).digest("base64url"),f=`${c}.${p}`,y=new URLSearchParams;y.set("grant_type","urn:ietf:params:oauth:grant-type:jwt-bearer"),y.set("client_id",t.clientId),y.set("assertion",f),y.set("scope",t.scope??"");let T=await e.post(t.tokenUrl,y.toString(),"application/x-www-form-urlencoded",{credentials:"include"});return(await JSON.parse(T)).access_token}async function Ht(e,t){let r=Fo(),o=jo(r,t.privateKeyPath),n=xt(o),a=Uo(n),s=await new ee({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti(Lo(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(a),c=new URLSearchParams;c.append("grant_type","client_credentials"),c.append("client_assertion_type","urn:ietf:params:oauth:client-assertion-type:jwt-bearer"),c.append("client_assertion",s);let p=await e.post(t.tokenUrl,c.toString(),"application/x-www-form-urlencoded",{credentials:"include"});if(!p.access_token)throw new Error(`Failed to login: ${p}`);return p.access_token}var kt="medplum-cli",Ot="http://localhost:9615",Ue=m("login"),Le=m("whoami");Ue.action(async e=>{let t=e.profile??"default",r=new E(t);if(Tt(r,t)||(console.log("Creating new profile..."),fe(t,e)),e.authType==="basic"){console.log("Basic authentication does not require login");return}let o=he(t),n=await u(e);await nn(n,o)});Le.action(async e=>{let t=await u(e);cn(t)});async function nn(e,t){if(!t?.authType){await dn(e);return}if(t.authType==="jwt-bearer"){if(!t.clientId||!t.clientSecret)throw new Error("Missing values, make sure to add --client-id, and --client-secret for JWT Bearer login");console.log("Starting JWT login...");let r=await It(e,t);new E(t.name).setObject("activeLogin",{accessToken:r})}else if(t.authType==="jwt-assertion"){let r=await Ht(e,t);new E(t.name).setObject("activeLogin",{accessToken:r})}console.log("Login successful")}async function an(e){let t=rn(async(r,o)=>{let n=new URL(r.url,"http://localhost:9615"),a=n.searchParams.get("code");if(n.pathname==="/"&&a)try{let s=await e.processCode(a,{clientId:kt,redirectUri:Ot});o.writeHead(200,{"Content-Type":Ne.TEXT}),o.end(`Signed in as ${Qo(s)}. You may close this window.`)}catch(s){o.writeHead(400,{"Content-Type":Ne.TEXT}),o.end(`Error: ${en(s)}`)}finally{t.close()}else o.writeHead(404,{"Content-Type":Ne.TEXT}),o.end("Not found")}).listen(9615)}async function sn(e){let t=on(),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)}tn(r)}function cn(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 dn(e){await an(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",kt),t.searchParams.set("redirect_uri",Ot),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await sn(t.toString())}import{Command as si}from"commander";import{CloudFormationClient as pn,DescribeStackResourcesCommand as mn,DescribeStacksCommand as un,ListStacksCommand as ln}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as fn}from"@aws-sdk/client-cloudfront";import{ECSClient as hn}from"@aws-sdk/client-ecs";import{S3Client as yn}from"@aws-sdk/client-s3";var $e=new pn({}),Wt=new fn({}),Rt=new hn({}),Mt=new yn({}),gn="medplum:environment";async function Be(){return(await $e.send(new ln({}))).StackSummaries?.filter(t=>t.StackName&&t.StackStatus!=="DELETE_COMPLETE")||[]}async function j(e){let t=await Be();for(let r of t){let o=r.StackName,n=await Fe(o);if(n?.tag===e)return n}}async function Fe(e){let t=new un({StackName:e}),o=(await $e.send(t))?.Stacks?.[0],n=o?.Tags?.find(c=>c.Key===gn);if(!n)return;let a=await $e.send(new mn({StackName:e}));if(!a.StackResources)return;let s={stack:o,tag:n.Value};for(let c of a.StackResources)c.ResourceType==="AWS::ECS::Cluster"?s.ecsCluster=c:c.ResourceType==="AWS::ECS::Service"?s.ecsService=c:c.ResourceType==="AWS::S3::Bucket"&&c.LogicalResourceId?.startsWith("FrontEndAppBucket")?s.appBucket=c:c.ResourceType==="AWS::S3::Bucket"&&c.LogicalResourceId?.startsWith("StorageStorageBucket")?s.storageBucket=c:c.ResourceType==="AWS::CloudFront::Distribution"&&c.LogicalResourceId?.startsWith("FrontEndAppDistribution")&&(s.appDistribution=c);return s}function ye(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: ${Ge(e.ecsService)}`),console.log(`App Bucket: ${e.appBucket?.PhysicalResourceId}`),console.log(`Storage Bucket: ${e.storageBucket?.PhysicalResourceId}`)}function Ge(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function Dt(e){let t=await j(e);if(!t){console.log("Stack not found");return}ye(t)}import{ACMClient as Ut,ListCertificatesCommand as wn,RequestCertificateCommand as Sn}from"@aws-sdk/client-acm";import{CloudFrontClient as En,CreatePublicKeyCommand as bn}from"@aws-sdk/client-cloudfront";import{GetParameterCommand as Cn,PutParameterCommand as vn,SSMClient as An}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as xn,STSClient as Pn}from"@aws-sdk/client-sts";import{generateKeyPairSync as _n,randomUUID as Jt}from"crypto";import{existsSync as Kn,writeFileSync as Tn}from"fs";import{resolve as In}from"path";import Hn from"readline";var kn=e=>`${e}DomainName`,Lt=e=>`${e}SslCertArn`,we;async function $t(){let e={apiPort:8103,region:"us-east-1"};we=Hn.createInterface({input:process.stdin,output:process.stdout}),h("MEDPLUM"),i("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),i(""),i("Most Medplum infrastructure is deployed using the AWS CDK."),i("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),i("This tool will help you create those resources."),i(""),i("Upon completion, this tool will:"),i(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),i(" 2. Optionally generate an AWS CloudFront signing key"),i(" 3. Optionally request SSL certificates from AWS Certificate Manager"),i(" 4. Optionally write server config settings to AWS Parameter Store"),i(""),i("The Medplum infra config file is an input to the Medplum CDK."),i("The Medplum CDK will create and manage the necessary AWS resources."),i(""),i("We will ask a series of questions to generate your infra config file."),i("Some questions have predefined options in [square brackets]."),i("Some questions have default values in (parentheses), which you can accept by pressing Enter."),i("Press Ctrl+C at any time to exit.");let t=await On(e.region);t||(i("It appears that you do not have AWS credentials configured."),i("AWS credentials are not strictly required, but will enable some additional features."),i("If you intend to use AWS credentials, please configure them now."),await ge("Do you want to continue without AWS credentials?")),h("ENVIRONMENT NAME"),i('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),i("The environment name is used in multiple places:"),i(" 1. As part of config file names (i.e., medplum.demo.config.json)"),i(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),i(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await K("What is your environment name?","demo"),i('Using environment name "'+e.name+'"...'),h("CONFIG FILE"),i("Medplum Infrastructure will create a config file in the current directory.");let r=await K("What is the config file name?",`medplum.${e.name}.config.json`);Kn(r)&&(i("Config file already exists."),await ge("Do you want to overwrite the config file?")),i('Using config file "'+r+'"...'),g(r,e),h("AWS REGION"),i("Most Medplum resources will be created in a single AWS region."),e.region=await K("Enter your AWS region:","us-east-1"),g(r,e),h("AWS ACCOUNT NUMBER"),i("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&i("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await K("What is your AWS account number?",t),g(r,e),h("STACK NAME"),i("Medplum will create a CloudFormation stack to manage AWS resources."),i("AWS CloudFormation stack names ");let o="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await K("Enter your CloudFormation stack name?",o),g(r,e),h("BASE DOMAIN NAME"),i("Please enter the base domain name for your Medplum deployment."),i(""),i("Medplum deploys multiple subdomains for various services."),i(""),i('For example, "api." for the REST API and "app." for the web application.'),i("The base domain name is the common suffix for all subdomains."),i(""),i('For example, if your base domain name is "example.com",'),i('then the REST API will be "api.example.com".'),i(""),i('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),i(""),i("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await K("Enter your base domain name:");g(r,e),h("SUPPORT EMAIL"),i("Medplum sends transactional emails to users."),i("For example, emails to new users or for password reset."),i("Medplum will use the support email address to send these emails."),i("Note that you must verify the support email address in SES.");let n=await K("Enter your support email address:");h("API DOMAIN NAME"),i("Medplum deploys a REST API for the backend services."),e.apiDomainName=await K("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,g(r,e),h("APP DOMAIN NAME"),i("Medplum deploys a web application for the user interface."),e.appDomainName=await K("Enter your web application domain name:","app."+e.domainName),g(r,e),h("STORAGE DOMAIN NAME"),i("Medplum deploys a storage service for file uploads."),e.storageDomainName=await K("Enter your storage domain name:","storage."+e.domainName),g(r,e),h("STORAGE BUCKET"),i("Medplum uses an S3 bucket to store binary content such as file uploads."),i("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await K("Enter your storage bucket name:","medplum-"+e.name+"-storage"),g(r,e),h("MAX AVAILABILITY ZONES"),i("Medplum API servers can be deployed in multiple availability zones."),i("This provides redundancy and high availability."),i("However, it also increases the cost of the deployment."),i("If you want to use all availability zones, choose a large number such as 99."),i("If you want to restrict the number, for example to manage EIP limits,"),i("then choose a small number such as 1 or 2."),e.maxAzs=await te("Enter the maximum number of availability zones:",[1,2,3,99],2),h("DATABASE INSTANCES"),i("Medplum uses a relational database to store data."),i("You can set up your own database,"),i("or Medplum can create a new RDS database as part of the CloudFormation stack."),await je("Do you want to create a new RDS database as part of the CloudFormation stack?")?(i("Medplum will create a new RDS database as part of the CloudFormation stack."),i(""),i("If you need high availability, you can choose multiple instances."),i("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await te("Enter the number of database instances:",[1,2],1)):(i("Medplum will not create a new RDS database."),i("Please create a new RDS database and enter the database name, username, and password."),i('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),e.rdsSecretsArn="TODO"),g(r,e),h("SERVER INSTANCES"),i("Medplum uses AWS Fargate to run the API servers."),i("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),i("Fargate will automatically scale the number of servers up and down."),i("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await te("Enter the number of server instances:",[1,2,3,4,6,8],1),g(r,e),h("SERVER MEMORY"),i("You can choose the amount of memory for each server instance."),i("The default is 512 MB, which is sufficient for getting started."),i("Note that only certain CPU units are compatible with memory units."),i('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await te("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),g(r,e),h("SERVER CPU"),i("You can choose the amount of CPU for each server instance."),i("CPU is expressed as an integer using AWS CPU units"),i("The default is 256, which is sufficient for getting started."),i("Note that only certain CPU units are compatible with memory units."),i('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await te("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),g(r,e),h("SERVER IMAGE"),i("Medplum uses Docker images for the API servers."),i("You can choose the image to use for the servers."),i("Docker images can be loaded from either Docker Hub or AWS ECR."),i("The default is the latest Medplum release."),e.serverImage=await K("Enter the server image:","medplum/medplum-server:latest"),g(r,e),h("SIGNING KEY"),i("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let{keyId:a,privateKey:s,publicKey:c,passphrase:p}=await Dn(e.stackName+"SigningKey");e.signingKeyId=a,e.storagePublicKey=c,g(r,e),h("SSL CERTIFICATES"),i("Medplum will now check for existing SSL certificates for the subdomains.");let f=await Wn(e.region);i("Found "+f.length+" certificate(s).");for(let{region:T,certName:I}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){i("");let lr=await Rn(e,f,T,I);e[Lt(I)]=lr,g(r,e)}h("AWS PARAMETER STORE"),i("Medplum uses AWS Parameter Store to store sensitive configuration values."),i("These values will be encrypted at rest."),i(`The values will be stored in the "/medplum/${e.name}" path.`);let y={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,signingKeyId:e.signingKeyId,signingKey:s,signingKeyPassphrase:p,supportEmail:n};i(JSON.stringify({...y,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await ge("Do you want to store these values in AWS Parameter Store?"),await Un(e.region,`/medplum/${e.name}/`,y),h("DONE!"),i("Medplum configuration complete."),i("You can now proceed to deploying the Medplum infrastructure with CDK."),i("Run:"),i(""),i(` npx cdk bootstrap -c config=${r}`),i(` npx cdk synth -c config=${r}`),e.region==="us-east-1"?i(` npx cdk deploy -c config=${r}`):i(` npx cdk deploy -c config=${r} --all`),i(""),i("See Medplum documentation for more information:"),i(""),i(" https://www.medplum.com/docs/self-hosting/install-on-aws"),i(""),we.close()}function i(e){we.write(e+`
|
|
2
|
+
var at=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import{MEDPLUM_VERSION as Wi,normalizeErrorString as Mi}from"@medplum/core";import{Command as Di}from"commander";import Ji from"dotenv";import{ContentType as Be,getDisplayString as tn,normalizeErrorString as rn}from"@medplum/core";import{exec as on}from"child_process";import{createServer as nn}from"http";import{platform as an}from"os";import{ClientStorage as br}from"@medplum/core";import{existsSync as st,mkdirSync as Er,readFileSync as Cr,writeFileSync as vr}from"fs";import{homedir as Ar}from"os";import{resolve as ct}from"path";var I=class extends br{constructor(r){super();this.dirName=ct(Ar(),".medplum"),this.fileName=ct(this.dirName,r+".json")}clear(){this.writeFile({})}getString(r){return this.readFile()?.[r]}setString(r,o){let n=this.readFile()??{};o?n[r]=o:delete n[r],this.writeFile(n)}getObject(r){let o=this.getString(r);return o?JSON.parse(o):void 0}setObject(r,o){this.setString(r,o?JSON.stringify(o):void 0)}readFile(){if(st(this.fileName))return JSON.parse(Cr(this.fileName,"utf8"))}writeFile(r){st(this.dirName)||Er(this.dirName),vr(this.fileName,JSON.stringify(r,null,2),"utf8")}};import{MedplumClient as Pr}from"@medplum/core";async function l(e){let t=e.profile??"default",r=new I(t),o=r.getObject("options");if(t!=="default"&&!o)throw new Error(`Profile "${t}" does not exist`);let{baseUrl:n,fhirUrlPath:a,accessToken:s,tokenUrl:c,authorizeUrl:d,clientId:u,clientSecret:K}=xr(e,r),k=e.fetch??fetch,_=new Pr({fetch:k,baseUrl:n,tokenUrl:c,fhirUrlPath:a,authorizeUrl:d,storage:r,onUnauthenticated:Ir,verbose:e.verbose});return s&&_.setAccessToken(s),o?.authType==="client_credentials"?(_.setBasicAuth(u,K),await _.startClientLogin(u,K)):o?.authType==="basic"&&_.setBasicAuth(u,K),_}function xr(e,t){let r=t.getObject("options"),o=e.baseUrl??r?.baseUrl??process.env.MEDPLUM_BASE_URL??"https://api.medplum.com/",n=e.fhirUrlPath??r?.fhirUrlPath??process.env.MEDPLUM_FHIR_URL_PATH,a=e.accessToken??r?.accessToken??process.env.MEDPLUM_CLIENT_ACCESS_TOKEN,s=e.tokenUrl??r?.tokenUrl??process.env.MEDPLUM_TOKEN_URL,c=e.authorizeUrl??r?.authorizeUrl??process.env.MEDPLUM_AUTHORIZE_URL,d=e.clientId??r?.clientId??process.env.MEDPLUM_CLIENT_ID,u=e.clientSecret??r?.clientSecret??process.env.MEDPLUM_CLIENT_SECRET;return{baseUrl:o,fhirUrlPath:n,accessToken:a,tokenUrl:s,authorizeUrl:c,clientId:d,clientSecret:u}}function Ir(){console.log("Unauthenticated: run `npx medplum login` to sign in")}import{Command as _r,Option as Tr}from"commander";function m(e){return new _r(e).option("--client-id <clientId>","FHIR server client id").option("--client-secret <clientSecret>","FHIR server client secret").option("--base-url <baseUrl>","FHIR server base URL, must be absolute").option("--token-url <tokenUrl>","FHIR server token URL, absolute or relative to base URL").option("--authorize-url <authorizeUrl>","FHIR server authorize URL, absolute or relative to base URL").option("--fhir-url, --fhir-url-path <fhirUrlPath>","FHIR server URL, absolute or relative to base URL").option("--scope <scope>","JWT scope").option("--access-token <accessToken>","Access token for token exchange authentication").option("--callback-url <callbackUrl>","Callback URL for authorization code flow").option("--subject <subject>","Subject for JWT authentication").option("--audience <audience>","Audience for JWT authentication").option("--issuer <issuer>","Issuer for JWT authentication").option("--private-key-path <privateKeyPath>","Private key path for JWT assertion").option("--audience <audience>","Audience for JWT assertion").option("-p, --profile <profile>","Profile name").option("-v --verbose","Verbose output").addOption(new Tr("--auth-type <authType>","Type of authentication").choices(["basic","client-credentials","authorization-code","jwt-bearer","token-exchange","jwt-assertion"]))}import{ContentType as De,encodeBase64 as It}from"@medplum/core";import{createHmac as Go,createPrivateKey as zo,randomBytes as Vo}from"crypto";import{existsSync as jo,readFileSync as _t,writeFileSync as qo}from"fs";import{Buffer as Ae}from"buffer";var C=new TextEncoder,S=new TextDecoder,ta=2**32;function T(...e){let t=e.reduce((n,{length:a})=>n+a,0),r=new Uint8Array(t),o=0;return e.forEach(n=>{r.set(n,o),o+=n.length}),r}var g;Ae.isEncoding("base64url")?g=e=>Ae.from(e).toString("base64url"):g=e=>Ae.from(e).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_");var L=class extends Error{static get code(){return"ERR_JOSE_GENERIC"}constructor(t){var r;super(t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}};var p=class extends L{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}};var v=class extends L{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}},W=class extends L{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}};import{KeyObject as Rr}from"crypto";import*as xe from"util";var A=xe.types.isKeyObject?e=>xe.types.isKeyObject(e):e=>e!=null&&e instanceof Rr;import*as pt from"crypto";import*as Ie from"util";var Or=pt.webcrypto,ie=Or,b=Ie.types.isCryptoKey?e=>Ie.types.isCryptoKey(e):e=>!1;function O(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function ae(e,t){return e.name===t}function _e(e){return parseInt(e.name.slice(4),10)}function Hr(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Wr(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let o=t.pop();r+=`one of ${t.join(", ")}, or ${o}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function mt(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!ae(e.algorithm,"HMAC"))throw O("HMAC");let o=parseInt(t.slice(2),10);if(_e(e.algorithm.hash)!==o)throw O(`SHA-${o}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ae(e.algorithm,"RSASSA-PKCS1-v1_5"))throw O("RSASSA-PKCS1-v1_5");let o=parseInt(t.slice(2),10);if(_e(e.algorithm.hash)!==o)throw O(`SHA-${o}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ae(e.algorithm,"RSA-PSS"))throw O("RSA-PSS");let o=parseInt(t.slice(2),10);if(_e(e.algorithm.hash)!==o)throw O(`SHA-${o}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw O("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!ae(e.algorithm,"ECDSA"))throw O("ECDSA");let o=Hr(t);if(e.algorithm.namedCurve!==o)throw O(o,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Wr(e,r)}function lt(e,t,...r){if(r.length>2){let o=r.pop();e+=`one of type ${r.join(", ")}, or ${o}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor&&t.constructor.name&&(e+=` Received an instance of ${t.constructor.name}`),e}var P=(e,...t)=>lt("Key must be ",e,...t);function Te(e,t,...r){return lt(`Key for the ${e} algorithm must be `,t,...r)}var Ke=e=>A(e)||b(e),f=["KeyObject"];(globalThis.CryptoKey||!(ie===null||ie===void 0)&&ie.CryptoKey)&&f.push("CryptoKey");import{promisify as ft}from"util";import{inflateRaw as Nr,deflateRaw as Lr}from"zlib";var Ga=ft(Nr),za=ft(Lr);var $r=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let o of t){let n=Object.keys(o);if(!r||r.size===0){r=new Set(n);continue}for(let a of n){if(r.has(a))return!1;r.add(a)}}return!0},$=$r;function Br(e){return typeof e=="object"&&e!==null}function w(e){if(!Br(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}import{diffieHellman as gs,generateKeyPair as Yr,KeyObject as ws}from"crypto";import{promisify as Zr}from"util";import{Buffer as se}from"buffer";import{createPublicKey as Fr,KeyObject as Gr}from"crypto";var zr=se.from([42,134,72,206,61,3,1,7]),Vr=se.from([43,129,4,0,34]),jr=se.from([43,129,4,0,35]),qr=se.from([43,129,4,0,10]),ke=new WeakMap,Xr=e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new p("Unsupported key curve for this operation")}},ht=(e,t)=>{var r;let o;if(b(e))o=Gr.from(e);else if(A(e))o=e;else throw new TypeError(P(e,...f));if(o.type==="secret")throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(o.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${o.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${o.asymmetricKeyType.slice(1)}`;case"ec":{if(ke.has(o))return ke.get(o);let n=(r=o.asymmetricKeyDetails)===null||r===void 0?void 0:r.namedCurve;if(!n&&o.type==="private")n=ht(Fr(o),!0);else if(!n){let s=o.export({format:"der",type:"spki"}),c=s[1]<128?14:15,d=s[c],u=s.slice(c+1,c+1+d);if(u.equals(zr))n="prime256v1";else if(u.equals(Vr))n="secp384r1";else if(u.equals(jr))n="secp521r1";else if(u.equals(qr))n="secp256k1";else throw new p("Unsupported key curve for this operation")}if(t)return n;let a=Xr(n);return ke.set(o,a),a}default:throw new TypeError("Invalid asymmetric key type for this operation")}};var ce=ht;var _s=Zr(Yr);import{promisify as to}from"util";import{KeyObject as Ws,pbkdf2 as ro}from"crypto";var zs=to(ro);var Re=new WeakMap,de=(e,t)=>{let r=e.readUInt8(1);if(!(r&128))return t===0?r:de(e.subarray(2+r),t-1);let o=r&127;r=0;for(let n=0;n<o;n++){r<<=8;let a=e.readUInt8(2+n);r|=a}return t===0?r:de(e.subarray(2+r),t-1)},oo=(e,t)=>{let r=e.readUInt8(1);if(!(r&128))return de(e.subarray(2),t);let o=r&127;return de(e.subarray(2+o),t)},no=e=>{var t,r;if(Re.has(e))return Re.get(e);let o=(r=(t=e.asymmetricKeyDetails)===null||t===void 0?void 0:t.modulusLength)!==null&&r!==void 0?r:oo(e.export({format:"der",type:"pkcs1"}),e.type==="private"?1:0)-1<<3;return Re.set(e,o),o};var X=(e,t)=>{if(no(e)<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)};import{Buffer as E}from"buffer";var io=2,ao=3,so=4,co=48,lc=E.from([0]),uc=E.from([io]),fc=E.from([ao]),hc=E.from([co]),yc=E.from([so]);var gc=new Map([["P-256",E.from("06 08 2A 86 48 CE 3D 03 01 07".replace(/ /g,""),"hex")],["secp256k1",E.from("06 05 2B 81 04 00 0A".replace(/ /g,""),"hex")],["P-384",E.from("06 05 2B 81 04 00 22".replace(/ /g,""),"hex")],["P-521",E.from("06 05 2B 81 04 00 23".replace(/ /g,""),"hex")],["ecPublicKey",E.from("06 07 2A 86 48 CE 3D 02 01".replace(/ /g,""),"hex")],["X25519",E.from("06 03 2B 65 6E".replace(/ /g,""),"hex")],["X448",E.from("06 03 2B 65 6F".replace(/ /g,""),"hex")],["Ed25519",E.from("06 03 2B 65 70".replace(/ /g,""),"hex")],["Ed448",E.from("06 03 2B 65 71".replace(/ /g,""),"hex")]]);var[D,pe]=process.versions.node.split(".").map(e=>parseInt(e,10)),gt=D>=16||D===15&&pe>=13,N=!("electron"in process.versions)&&(D>=17||D===16&&pe>=9),po=D>=16||D===15&&pe>=9,mo=D>=16||D===15&&pe>=12;var uo=(e,t)=>{if(!(t instanceof Uint8Array)){if(!Ke(t))throw new TypeError(Te(e,t,...f,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${f.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},fo=(e,t,r)=>{if(!Ke(t))throw new TypeError(Te(e,t,...f));if(t.type==="secret")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${f.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},ho=(e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?uo(e,t):fo(e,t,r)},Y=ho;function Co(e,t,r,o,n){if(n.crit!==void 0&&o.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!o||o.crit===void 0)return new Set;if(!Array.isArray(o.crit)||o.crit.length===0||o.crit.some(s=>typeof s!="string"||s.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let a;r!==void 0?a=new Map([...Object.entries(r),...t.entries()]):a=t;for(let s of o.crit){if(!a.has(s))throw new p(`Extension Header Parameter "${s}" is not recognized`);if(n[s]===void 0)throw new e(`Extension Header Parameter "${s}" is missing`);if(a.get(s)&&o[s]===void 0)throw new e(`Extension Header Parameter "${s}" MUST be integrity protected`)}return new Set(o.crit)}var F=Co;var Io=Symbol();import*as Z from"crypto";import{promisify as Ro}from"util";function me(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"EdDSA":return;default:throw new p(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import{constants as Et}from"crypto";var Ct={padding:Et.RSA_PKCS1_PSS_PADDING,saltLength:Et.RSA_PSS_SALTLEN_DIGEST},_o=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function le(e,t){switch(e){case"EdDSA":if(!["ed25519","ed448"].includes(t.asymmetricKeyType))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");return t;case"RS256":case"RS384":case"RS512":if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");return X(t,e),t;case(N&&"PS256"):case(N&&"PS384"):case(N&&"PS512"):if(t.asymmetricKeyType==="rsa-pss"){let{hashAlgorithm:r,mgf1HashAlgorithm:o,saltLength:n}=t.asymmetricKeyDetails,a=parseInt(e.slice(-3),10);if(r!==void 0&&(r!==`sha${a}`||o!==r))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(n!==void 0&&n>a>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");return X(t,e),{key:t,...Ct};case(!N&&"PS256"):case(!N&&"PS384"):case(!N&&"PS512"):if(t.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");return X(t,e),{key:t,...Ct};case"ES256":case"ES256K":case"ES384":case"ES512":{if(t.asymmetricKeyType!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let r=ce(t),o=_o.get(e);if(r!==o)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${o}, got ${r}`);return{dsaEncoding:"ieee-p1363",key:t}}default:throw new p(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import*as G from"crypto";import{promisify as Ko}from"util";function He(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new p(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}import{KeyObject as vt,createSecretKey as To}from"crypto";function ue(e,t,r){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(P(t,...f));return To(t)}if(t instanceof vt)return t;if(b(t))return mt(t,e,r),vt.from(t);throw new TypeError(P(t,...f,"Uint8Array"))}var We;G.sign.length>3?We=Ko(G.sign):We=G.sign;var ko=async(e,t,r)=>{let o=ue(e,t,"sign");if(e.startsWith("HS")){let n=G.createHmac(He(e),o);return n.update(r),n.digest()}return We(me(e),r,le(e,o))},Me=ko;var At;Z.verify.length>4&>?At=Ro(Z.verify):At=Z.verify;var Q=e=>Math.floor(e.getTime()/1e3);var Ho=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,fe=e=>{let t=Ho.exec(e);if(!t)throw new TypeError("Invalid time period format");let r=parseFloat(t[1]);switch(t[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(r);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(r*60);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(r*3600);case"day":case"days":case"d":return Math.round(r*86400);case"week":case"weeks":case"w":return Math.round(r*604800);default:return Math.round(r*31557600)}};var z=class{constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new v("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!$(this._protectedHeader,this._unprotectedHeader))throw new v("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let o={...this._protectedHeader,...this._unprotectedHeader},n=F(v,new Map([["b64",!0]]),r?.crit,this._protectedHeader,o),a=!0;if(n.has("b64")&&(a=this._protectedHeader.b64,typeof a!="boolean"))throw new v('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=o;if(typeof s!="string"||!s)throw new v('JWS "alg" (Algorithm) Header Parameter missing or invalid');Y(s,t,"sign");let c=this._payload;a&&(c=C.encode(g(c)));let d;this._protectedHeader?d=C.encode(g(JSON.stringify(this._protectedHeader))):d=C.encode("");let u=T(d,C.encode("."),c),K=await Me(s,t,u),k={signature:g(K),payload:""};return a&&(k.payload=S.decode(c)),this._unprotectedHeader&&(k.header=this._unprotectedHeader),this._protectedHeader&&(k.protected=S.decode(d)),k}};var ee=class{constructor(t){this._flattened=new z(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let o=await this._flattened.sign(t,r);if(o.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${o.protected}.${o.payload}.${o.signature}`}};var V=class{constructor(t){if(!w(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:t}:this._payload={...this._payload,nbf:Q(new Date)+fe(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:t}:this._payload={...this._payload,exp:Q(new Date)+fe(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:Q(new Date)}:this._payload={...this._payload,iat:t},this}};var te=class extends V{setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){var o;let n=new ee(C.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray((o=this._protectedHeader)===null||o===void 0?void 0:o.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new W("JWTs MUST NOT use unencoded payload");return n.sign(t,r)}};import{createSecretKey as hu,generateKeyPair as Bo}from"crypto";import{promisify as Fo}from"util";var bu=Fo(Bo);import{basename as Tt,extname as Xo,resolve as Kt}from"path";import Yo from"tar";function H(e){console.log(JSON.stringify(e,null,2))}async function Je(e,t,r){let o=t.source,n=Le(o);if(n)try{console.log("Saving source code...");let a=await e.createAttachment(n,Tt(o),en(o));console.log("Updating bot.....");let s=await e.updateResource({...r,sourceCode:a});console.log("Success! New bot version: "+s.meta?.versionId)}catch(a){console.log("Update error: ",a)}}async function Ue(e,t,r){let o=t.dist??t.source,n=Le(o);if(n)try{console.log("Deploying bot...");let a=await e.post(e.fhirUrl("Bot",r.id,"$deploy"),{code:n,filename:Tt(o)});console.log("Deploy result: "+a.issue?.[0]?.details?.text)}catch(a){console.log("Deploy error: ",a)}}async function Ne(e,t,r,o,n,a){try{let s={name:t,description:"",runtimeVersion:a},c=await e.post("admin/projects/"+r+"/bot",s),d=await e.readResource("Bot",c.id),u={name:t,id:c.id,source:o,dist:n};await Je(e,u,d),await Ue(e,u,d),console.log(`Success! Bot created: ${d.id}`),Zo(u)}catch(s){console.log("Error while creating new bot: "+s)}}function kt(e){let t=new RegExp("^"+Qo(e).replace(/\\\*/g,".*")+"$"),r=j()?.bots?.filter(o=>t.test(o.name));return r||[]}function j(e){let t=e?`medplum.${e}.config.json`:"medplum.config.json",r=Le(t);if(r)return JSON.parse(r)}function Le(e){let t=Kt(process.cwd(),e);return jo(t)?_t(t,"utf8"):""}function Zo(e){let t=j()??{};t.bots||(t.bots=[]),t.bots.push(e),qo("medplum.config.json",JSON.stringify(t,null,2),"utf8"),console.log(`Bot added to config: ${e.id}`)}function Qo(e){return e.replace(/[/\-\\^$*+?.()|[\]{}]/g,"\\$&")}function Rt(e){let o=0,n=0;return Yo.x({cwd:e,filter:(a,s)=>{if(o++,o>100)throw new Error("Tar extractor reached max number of files");if(n+=s.size,n>10485760)throw new Error("Tar extractor reached max size");return!0}})}function $e(){return{extension:[{url:"http://hl7.org/fhir/StructureDefinition/data-absent-reason",valueCode:"unsupported"}]}}function en(e){let t=Xo(e).toLowerCase();return[".cjs",".mjs",".js"].includes(t)?De.JAVASCRIPT:[".cts",".mts",".ts"].includes(t)?De.TYPESCRIPT:De.TEXT}function he(e,t){let r=new I(e),o={name:e,...t};r.setObject("options",o),console.log(`${e} profile created`)}function ye(e){return new I(e).getObject("options")}function Ot(e,t){return t==="default"?!0:!!e.getObject("options")}async function Ht(e,t){let r={typ:"JWT",alg:"HS256"},o=Math.floor(Date.now()/1e3),n={aud:`${t.baseUrl}${t.audience}`,iss:t.issuer,sub:t.subject,nbf:o,iat:o,exp:o+604800},a=It(JSON.stringify(r)),s=It(JSON.stringify(n)),c=`${a}.${s}`,d=Go("sha256",t.clientSecret).update(c).digest("base64url"),u=`${c}.${d}`;await e.startJwtBearerLogin(t.clientId,u,t.scope??"")}async function Wt(e,t){let r=zo(_t(Kt(t.privateKeyPath))),o=await new te({}).setProtectedHeader({alg:"RS384",typ:"JWT"}).setIssuer(t.clientId).setSubject(t.clientId).setAudience(`${t.baseUrl}${t.audience}`).setJti(Vo(16).toString("hex")).setIssuedAt().setExpirationTime("5m").sign(r);await e.startJwtAssertionLogin(o)}var Mt="medplum-cli",Dt="http://localhost:9615",Fe=m("login"),Ge=m("whoami");Fe.action(async e=>{let t=e.profile??"default",r=new I(t);if(Ot(r,t)||(console.log("Creating new profile..."),he(t,e)),e.authType==="basic"){console.log("Basic authentication does not require login");return}let o=ye(t),n=await l(e);await sn(n,o)});Ge.action(async e=>{let t=await l(e);pn(t)});async function sn(e,t){if(!t?.authType){await mn(e);return}if(t.authType==="jwt-bearer"){if(!t.clientId||!t.clientSecret)throw new Error("Missing values, make sure to add --client-id, and --client-secret for JWT Bearer login");console.log("Starting JWT login..."),await Ht(e,t)}else t.authType==="jwt-assertion"&&await Wt(e,t);console.log("Login successful")}async function cn(e){let t=nn(async(r,o)=>{let n=new URL(r.url,"http://localhost:9615"),a=n.searchParams.get("code");if(n.pathname==="/"&&a)try{let s=await e.processCode(a,{clientId:Mt,redirectUri:Dt});o.writeHead(200,{"Content-Type":Be.TEXT}),o.end(`Signed in as ${tn(s)}. You may close this window.`)}catch(s){o.writeHead(400,{"Content-Type":Be.TEXT}),o.end(`Error: ${rn(s)}`)}finally{t.close()}else o.writeHead(404,{"Content-Type":Be.TEXT}),o.end("Not found")}).listen(9615)}async function dn(e){let t=an(),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)}on(r)}function pn(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 mn(e){await cn(e);let t=new URL(e.getAuthorizeUrl());t.searchParams.set("client_id",Mt),t.searchParams.set("redirect_uri",Dt),t.searchParams.set("scope","openid"),t.searchParams.set("response_type","code"),t.searchParams.set("prompt","login"),await dn(t.toString())}import{Command as hi}from"commander";import{CloudFormationClient as Ut,DescribeStackResourcesCommand as ln,DescribeStacksCommand as un,ListStacksCommand as fn}from"@aws-sdk/client-cloudformation";import{CloudFrontClient as hn,CreateInvalidationCommand as yn}from"@aws-sdk/client-cloudfront";import{ECSClient as gn}from"@aws-sdk/client-ecs";import{S3Client as wn}from"@aws-sdk/client-s3";var ge=new Ut({}),Sn=new hn({region:"us-east-1"}),Nt=new gn({}),re=new wn({}),bn="medplum:environment";async function ze(){return(await ge.send(new fn({}))).StackSummaries?.filter(t=>t.StackName&&t.StackStatus!=="DELETE_COMPLETE")||[]}async function J(e){let t=await ze();for(let r of t){let o=r.StackName,n=await Ve(o);if(n?.tag===e)return n}}async function Ve(e){let t={};return await Jt(ge,e,t),ge.config.region!=="us-east-1"&&await Jt(new Ut({region:"us-east-1"}),e+"-us-east-1",t),t}async function Jt(e,t,r){let o=new un({StackName:t}),a=(await e.send(o))?.Stacks?.[0],s=a?.Tags?.find(d=>d.Key===bn);if(!s)return;let c=await e.send(new ln({StackName:t}));if(c.StackResources){e===ge&&(r.stack=a,r.tag=s.Value);for(let d of c.StackResources)En(d,r)}}function En(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 we(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: ${je(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 je(e){return e?.PhysicalResourceId?.split("/")?.pop()||""}async function Se(e){let t=await Sn.send(new yn({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}async function Lt(e){let t=await J(e);if(!t){console.log("Stack not found");return}we(t)}import{ACMClient as Ft,ListCertificatesCommand as Cn,RequestCertificateCommand as vn}from"@aws-sdk/client-acm";import{CloudFrontClient as An,CreatePublicKeyCommand as Pn}from"@aws-sdk/client-cloudfront";import{GetParameterCommand as xn,PutParameterCommand as In,SSMClient as _n}from"@aws-sdk/client-ssm";import{GetCallerIdentityCommand as Tn,STSClient as Kn}from"@aws-sdk/client-sts";import{generateKeyPairSync as kn,randomUUID as $t}from"crypto";import{existsSync as Rn,writeFileSync as On}from"fs";import{resolve as Hn}from"path";import Wn from"readline";var Mn=e=>`${e}DomainName`,Gt=e=>`${e}SslCertArn`,Ee;async function zt(){let e={apiPort:8103,region:"us-east-1"};Ee=Wn.createInterface({input:process.stdin,output:process.stdout}),h("MEDPLUM"),i("This tool prepares the necessary prerequisites for deploying Medplum in your AWS account."),i(""),i("Most Medplum infrastructure is deployed using the AWS CDK."),i("However, some AWS resources must be created manually, such as email addresses and SSL certificates."),i("This tool will help you create those resources."),i(""),i("Upon completion, this tool will:"),i(" 1. Generate a Medplum CDK config file (i.e., medplum.demo.config.json)"),i(" 2. Optionally generate an AWS CloudFront signing key"),i(" 3. Optionally request SSL certificates from AWS Certificate Manager"),i(" 4. Optionally write server config settings to AWS Parameter Store"),i(""),i("The Medplum infra config file is an input to the Medplum CDK."),i("The Medplum CDK will create and manage the necessary AWS resources."),i(""),i("We will ask a series of questions to generate your infra config file."),i("Some questions have predefined options in [square brackets]."),i("Some questions have default values in (parentheses), which you can accept by pressing Enter."),i("Press Ctrl+C at any time to exit.");let t=await Dn(e.region);t||(i("It appears that you do not have AWS credentials configured."),i("AWS credentials are not strictly required, but will enable some additional features."),i("If you intend to use AWS credentials, please configure them now."),await be("Do you want to continue without AWS credentials?")),h("ENVIRONMENT NAME"),i('Medplum deployments have a short environment name such as "prod", "staging", "alice", or "demo".'),i("The environment name is used in multiple places:"),i(" 1. As part of config file names (i.e., medplum.demo.config.json)"),i(" 2. As the base of CloudFormation stack names (i.e., MedplumDemo)"),i(" 3. AWS Parameter Store keys (i.e., /medplum/demo/...)"),e.name=await x("What is your environment name?","demo"),i('Using environment name "'+e.name+'"...'),h("CONFIG FILE"),i("Medplum Infrastructure will create a config file in the current directory.");let r=await x("What is the config file name?",`medplum.${e.name}.config.json`);Rn(r)&&(i("Config file already exists."),await be("Do you want to overwrite the config file?")),i('Using config file "'+r+'"...'),y(r,e),h("AWS REGION"),i("Most Medplum resources will be created in a single AWS region."),e.region=await x("Enter your AWS region:","us-east-1"),y(r,e),h("AWS ACCOUNT NUMBER"),i("Medplum Infrastructure will use your AWS account number to create AWS resources."),t&&i("Using the AWS CLI, your current account ID is: "+t),e.accountNumber=await x("What is your AWS account number?",t),y(r,e),h("STACK NAME"),i("Medplum will create a CloudFormation stack to manage AWS resources."),i("AWS CloudFormation stack names ");let o="Medplum"+e.name.charAt(0).toUpperCase()+e.name.slice(1);for(e.stackName=await x("Enter your CloudFormation stack name?",o),y(r,e),h("BASE DOMAIN NAME"),i("Please enter the base domain name for your Medplum deployment."),i(""),i("Medplum deploys multiple subdomains for various services."),i(""),i('For example, "api." for the REST API and "app." for the web application.'),i("The base domain name is the common suffix for all subdomains."),i(""),i('For example, if your base domain name is "example.com",'),i('then the REST API will be "api.example.com".'),i(""),i('The base domain should include the TLD (i.e., ".com", ".org", ".net").'),i(""),i("Note that you must own the base domain, and it must use Route53 DNS.");!e.domainName;)e.domainName=await x("Enter your base domain name:");y(r,e),h("SUPPORT EMAIL"),i("Medplum sends transactional emails to users."),i("For example, emails to new users or for password reset."),i("Medplum will use the support email address to send these emails."),i("Note that you must verify the support email address in SES.");let n=await x("Enter your support email address:");h("API DOMAIN NAME"),i("Medplum deploys a REST API for the backend services."),e.apiDomainName=await x("Enter your REST API domain name:","api."+e.domainName),e.baseUrl=`https://${e.apiDomainName}/`,y(r,e),h("APP DOMAIN NAME"),i("Medplum deploys a web application for the user interface."),e.appDomainName=await x("Enter your web application domain name:","app."+e.domainName),y(r,e),h("STORAGE DOMAIN NAME"),i("Medplum deploys a storage service for file uploads."),e.storageDomainName=await x("Enter your storage domain name:","storage."+e.domainName),y(r,e),h("STORAGE BUCKET"),i("Medplum uses an S3 bucket to store binary content such as file uploads."),i("Medplum will create a the S3 bucket as part of the CloudFormation stack."),e.storageBucketName=await x("Enter your storage bucket name:","medplum-"+e.name+"-storage"),y(r,e),h("MAX AVAILABILITY ZONES"),i("Medplum API servers can be deployed in multiple availability zones."),i("This provides redundancy and high availability."),i("However, it also increases the cost of the deployment."),i("If you want to use all availability zones, choose a large number such as 99."),i("If you want to restrict the number, for example to manage EIP limits,"),i("then choose a small number such as 1 or 2."),e.maxAzs=await oe("Enter the maximum number of availability zones:",[1,2,3,99],2),h("DATABASE INSTANCES"),i("Medplum uses a relational database to store data."),i("You can set up your own database,"),i("or Medplum can create a new RDS database as part of the CloudFormation stack."),await Xe("Do you want to create a new RDS database as part of the CloudFormation stack?")?(i("Medplum will create a new RDS database as part of the CloudFormation stack."),i(""),i("If you need high availability, you can choose multiple instances."),i("Use 1 for a single instance, or 2 for a primary and a standby."),e.rdsInstances=await oe("Enter the number of database instances:",[1,2],1)):(i("Medplum will not create a new RDS database."),i("Please create a new RDS database and enter the database name, username, and password."),i('Set the AWS Secrets Manager secret ARN in the config file in the "rdsSecretsArn" setting.'),e.rdsSecretsArn="TODO"),y(r,e),h("SERVER INSTANCES"),i("Medplum uses AWS Fargate to run the API servers."),i("Medplum will create a new Fargate cluster as part of the CloudFormation stack."),i("Fargate will automatically scale the number of servers up and down."),i("If you need high availability, you can choose multiple instances."),e.desiredServerCount=await oe("Enter the number of server instances:",[1,2,3,4,6,8],1),y(r,e),h("SERVER MEMORY"),i("You can choose the amount of memory for each server instance."),i("The default is 512 MB, which is sufficient for getting started."),i("Note that only certain CPU units are compatible with memory units."),i('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverMemory=await oe("Enter the server memory (MB):",[512,1024,2048,4096,8192,16384],512),y(r,e),h("SERVER CPU"),i("You can choose the amount of CPU for each server instance."),i("CPU is expressed as an integer using AWS CPU units"),i("The default is 256, which is sufficient for getting started."),i("Note that only certain CPU units are compatible with memory units."),i('Consult AWS Fargate "Task Definition Parameters" for more information.'),e.serverCpu=await oe("Enter the server CPU:",[256,512,1024,2048,4096,8192,16384],256),y(r,e),h("SERVER IMAGE"),i("Medplum uses Docker images for the API servers."),i("You can choose the image to use for the servers."),i("Docker images can be loaded from either Docker Hub or AWS ECR."),i("The default is the latest Medplum release."),e.serverImage=await x("Enter the server image:","medplum/medplum-server:latest"),y(r,e),h("SIGNING KEY"),i("Medplum uses AWS CloudFront Presigned URLs for binary content such as file uploads.");let{keyId:a,privateKey:s,publicKey:c,passphrase:d}=await Ln(e.stackName+"SigningKey");e.signingKeyId=a,e.storagePublicKey=c,y(r,e),h("SSL CERTIFICATES"),i("Medplum will now check for existing SSL certificates for the subdomains.");let u=await Jn(e.region);i("Found "+u.length+" certificate(s).");for(let{region:k,certName:_}of[{region:e.region,certName:"api"},{region:"us-east-1",certName:"app"},{region:"us-east-1",certName:"storage"}]){i("");let Sr=await Un(e,u,k,_);e[Gt(_)]=Sr,y(r,e)}h("AWS PARAMETER STORE"),i("Medplum uses AWS Parameter Store to store sensitive configuration values."),i("These values will be encrypted at rest."),i(`The values will be stored in the "/medplum/${e.name}" path.`);let K={port:e.apiPort,baseUrl:e.baseUrl,appBaseUrl:`https://${e.appDomainName}/`,storageBaseUrl:`https://${e.storageDomainName}/binary/`,binaryStorage:`s3:${e.storageBucketName}`,signingKeyId:e.signingKeyId,signingKey:s,signingKeyPassphrase:d,supportEmail:n};i(JSON.stringify({...K,signingKey:"****",signingKeyPassphrase:"****"},null,2)),await be("Do you want to store these values in AWS Parameter Store?"),await Fn(e.region,`/medplum/${e.name}/`,K),h("DONE!"),i("Medplum configuration complete."),i("You can now proceed to deploying the Medplum infrastructure with CDK."),i("Run:"),i(""),i(` npx cdk bootstrap -c config=${r}`),i(` npx cdk synth -c config=${r}`),e.region==="us-east-1"?i(` npx cdk deploy -c config=${r}`):i(` npx cdk deploy -c config=${r} --all`),i(""),i("See Medplum documentation for more information:"),i(""),i(" https://www.medplum.com/docs/self-hosting/install-on-aws"),i(""),Ee.close()}function i(e){Ee.write(e+`
|
|
3
3
|
`)}function h(e){i(`
|
|
4
4
|
`+e+`
|
|
5
|
-
`)}function K(e,t=""){return new Promise(r=>{we.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function ze(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await K(o)||r;if(t.includes(n))return n;i("Please choose one of the following options: "+t.join(", "))}}async function te(e,t,r){return parseInt(await ze(e,t.map(o=>o.toString()),r.toString()),10)}async function je(e){return(await ze(e,["y","n"])).toLowerCase()==="y"}async function ge(e){if(!await je(e))throw i("Exiting..."),new Error("User cancelled")}function g(e,t){Tn(In(e),JSON.stringify(t,void 0,2),"utf-8")}async function On(e){try{let t=new Pn({region:e}),r=new xn({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Wn(e){let t=await Nt(e);if(e!=="us-east-1"){let r=await Nt("us-east-1");t.push(...r)}return t}async function Nt(e){try{let t=new Ut({region:e}),r=new wn({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Rn(e,t,r,o){let n=e[kn(o)],a=t.find(c=>c.CertificateArn?.includes(r)&&c.DomainName===n);if(a)return i(`Found existing certificate for "${n}" in "${r}.`),a.CertificateArn;if(i(`No existing certificate found for "${n}" in "${r}.`),!await je("Do you want to request a new certificate?"))return i(`Please add your certificate ARN to the config file in the "${Lt(o)}" setting.`),"TODO";let s=await Mn(r,n);return i("Certificate ARN: "+s),s}async function Mn(e,t){try{let r=await ze("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new Ut({region:e}),n=new Sn({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 Dn(e){let t=Jt(),r=_n("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:t}});return{keyId:(await new En({}).send(new bn({PublicKeyConfig:{Name:e,CallerReference:Jt(),EncodedKey:r.publicKey}}))).PublicKey?.Id,publicKey:r.publicKey,privateKey:r.privateKey,passphrase:t}}async function Jn(e,t){let r=new Cn({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Nn(e,t,r){let o=new vn({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}async function Un(e,t,r){let o=new An({region:e});for(let[n,a]of Object.entries(r)){let s=t+n,c=a.toString(),p=await Jn(o,s);p!==void 0&&p!==c&&(i(`Parameter "${s}" exists with different value.`),await ge(`Do you want to overwrite "${s}"?`)),await Nn(o,s,c)}}async function Bt(){let e=await Be();for(let t of e){let r=t.StackName,o=await Fe(r);o&&(ye(o),console.log(""))}}import{CreateInvalidationCommand as Ln}from"@aws-sdk/client-cloudfront";import{PutObjectCommand as $n}from"@aws-sdk/client-s3";import{ContentType as k}from"@medplum/core";import Bn from"fast-glob";import{createReadStream as Fn,mkdtempSync as Gn,readdirSync as zn,readFileSync as jn,rmSync as Vn,writeFileSync as qn}from"fs";import Ft from"node-fetch";import{tmpdir as Xn}from"os";import{join as Se,sep as Yn}from"path";import{pipeline as Zn}from"stream/promises";async function Gt(e,t){let r=le(e);if(!r){console.log("Config not found");return}let o=await j(e);if(!o){console.log("Stack not found");return}let n=o.appBucket;if(!n){console.log("App bucket not found");return}let a=await ei("@medplum/app","latest");zt(a,{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 ri(a,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await ii(o.appDistribution.PhysicalResourceId),console.log("Done")}async function Qn(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await Ft(r)).json()}async function ei(e,t){let o=(await Qn(e,t)).dist.tarball,n=Gn(Se(Xn(),"tarball-"));try{let a=await Ft(o),s=Kt(n);return await Zn(a.body,s),Se(n,"package","dist")}catch(a){throw Vn(n,{recursive:!0,force:!0}),a}}function zt(e,t){for(let r of zn(e,{withFileTypes:!0})){let o=Se(e,r.name);r.isDirectory()?zt(o,t):r.isFile()&&o.endsWith(".js")&&ti(o,t)}}function ti(e,t){let r=jn(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);qn(e,r)}async function ri(e,t,r){let o=[["assets/**/*.css",k.CSS,!0],["assets/**/*.css.map",k.JSON,!0],["assets/**/*.js",k.JAVASCRIPT,!0],["assets/**/*.js.map",k.JSON,!0],["assets/**/*.txt",k.TEXT,!0],["assets/**/*.ico",k.FAVICON,!0],["img/**/*.png",k.PNG,!0],["img/**/*.svg",k.SVG,!0],["robots.txt",k.TEXT,!0],["index.html",k.HTML,!1]];for(let n of o)await oi({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function oi(e){let t=Bn.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await ni(Se(e.rootDir,r),e)}async function ni(e,t){let r=Fn(e),o=e.substring(t.rootDir.length+1).split(Yn).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 Mt.send(new $n(n))}async function ii(e){let t=await Wt.send(new Ln({DistributionId:e,InvalidationBatch:{CallerReference:`invalidate-all-${Date.now()}`,Paths:{Quantity:1,Items:["/*"]}}}));console.log(`Created invalidation with ID: ${t.Invalidation?.Id}`)}import{UpdateServiceCommand as ai}from"@aws-sdk/client-ecs";async function jt(e){let t=await j(e);if(!t){console.log("Stack not found");return}let r=t.ecsCluster?.PhysicalResourceId;if(!r){console.log("ECS Cluster not found");return}let o=Ge(t.ecsService);if(!o){console.log("ECS Service not found");return}await Rt.send(new ai({cluster:r,service:o,forceNewDeployment:!0})),console.log(`Service "${o}" updated successfully.`)}var N=new si("aws").description("Commands to manage AWS resources");N.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action($t);N.command("list").description("List Medplum AWS CloudFormation stacks").action(Bt);N.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>").action(Dt);N.command("update-server").alias("deploy-server").description("Update the server image").argument("<tag>").action(jt);N.command("update-app").alias("deploy-app").description("Update the app site").argument("<tag>").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(Gt);import{Command as ci}from"commander";var Vt=m("save"),qt=m("deploy"),Xt=m("create"),Yt=new ci("bot").addCommand(Vt).addCommand(qt).addCommand(Xt),Ve=m("save-bot"),qe=m("deploy-bot"),Xe=m("create-bot");Vt.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await u(t);await Ee(r,e)});qt.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await u(t);await Ee(r,e,!0)});Xt.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creating a bot").action(async(e,t,r,o,n)=>{let a=await u(n);await Me(a,[e,t,r,o])});async function Ee(e,t,r=!1){let o=_t(t);for(let n of o){let a=await e.readResource("Bot",n.id);await Re(e,n,a),r&&await Pt(e,n,a)}console.log(`Number of bots deployed: ${o.length}`)}Ve.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await u(t);await Ee(r,e)});qe.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await u(t);await Ee(r,e,!0)});Xe.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let a=await u(n);await Me(a,[e,t,r,o])});import{Command as di}from"commander";import{createReadStream as pi,writeFile as mi}from"fs";import{resolve as Qt}from"path";import{createInterface as ui}from"readline";var er=m("export"),tr=m("import"),rr=new di("bulk").addCommand(er).addCommand(tr);er.option("-e, --export-level <exportLevel>",'Optional export level. Defaults to system level export. "Group/:id" - Group of Patients, "Patient" - All Patients.').option("-t, --types <types>","optional resource types to export").option("-s, --since <since>","optional Resources will be included in the response if their state has changed after the supplied time (e.g. if Resource.meta.lastUpdated is later than the supplied _since time).").option("-d, --target-directory <targetDirectory>","optional target directory to save files from the bulk export operations.").action(async e=>{let{exportLevel:t,types:r,since:o,targetDirectory:n}=e,a=await u(e);(await a.bulkExport(t,r,o)).output?.forEach(async({type:c,url:p})=>{let f=new URL(p),y=await a.download(p),T=`${c}_${f.pathname}`.replace(/[^a-zA-Z0-9]+/g,"_")+".ndjson",I=Qt(n??"",T);mi(`${I}`,await y.text(),()=>{console.log(`${I} is created`)})})});tr.argument("<filename>","File Name").option("--num-resources-per-request <numResourcesPerRequest>","optional number of resources to import per batch request. Defaults to 25.","25").option("--add-extensions-for-missing-values","optional flag to add extensions for missing values in a resource",!1).option("-d, --target-directory <targetDirectory>","optional target directory of file to be imported").action(async(e,t)=>{let{numResourcesPerRequest:r,addExtensionsForMissingValues:o,targetDirectory:n}=t,a=Qt(n??process.cwd(),e),s=await u(t);await li(a,parseInt(r,10),s,o)});async function li(e,t,r,o){let n=[],a=pi(e),s=ui({input:a});for await(let c of s){let p=fi(c,o);n.push({resource:p,request:{method:"POST",url:p.resourceType}}),n.length%t===0&&(await Zt(n,r),n=[])}n.length>0&&await Zt(n,r)}async function Zt(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(o=>{W(o.response)})}function fi(e,t){let r=JSON.parse(e);return t?hi(r):r}function hi(e){return e.resourceType==="ExplanationOfBenefit"?yi(e):e}function yi(e){return e.provider||(e.provider=Je()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=Je())}),e}import{Command as gi,Option as wi}from"commander";var or=m("list"),nr=m("current"),ir=m("switch"),ar=m("invite"),sr=new gi("project").addCommand(or).addCommand(nr).addCommand(ir).addCommand(ar);or.description("List of current projects").action(async e=>{let t=await u(e);Si(t)});function Si(e){let r=e.getLogins().map(o=>`${o.project.display} (${o.project.reference})`).join(`
|
|
5
|
+
`)}function x(e,t=""){return new Promise(r=>{Ee.question(e+(t?" ("+t+")":"")+" ",o=>{r(o||t.toString())})})}async function qe(e,t,r=""){let o=e+" ["+t.map(n=>n===r?"("+n+")":n).join("|")+"]";for(;;){let n=await x(o)||r;if(t.includes(n))return n;i("Please choose one of the following options: "+t.join(", "))}}async function oe(e,t,r){return parseInt(await qe(e,t.map(o=>o.toString()),r.toString()),10)}async function Xe(e){return(await qe(e,["y","n"])).toLowerCase()==="y"}async function be(e){if(!await Xe(e))throw i("Exiting..."),new Error("User cancelled")}function y(e,t){On(Hn(e),JSON.stringify(t,void 0,2),"utf-8")}async function Dn(e){try{let t=new Kn({region:e}),r=new Tn({});return(await t.send(r)).Account}catch(t){console.log("Warning: Unable to get AWS account ID",t.message);return}}async function Jn(e){let t=await Bt(e);if(e!=="us-east-1"){let r=await Bt("us-east-1");t.push(...r)}return t}async function Bt(e){try{let t=new Ft({region:e}),r=new Cn({MaxItems:1e3});return(await t.send(r)).CertificateSummaryList}catch(t){return console.log("Warning: Unable to list certificates",t.message),[]}}async function Un(e,t,r,o){let n=e[Mn(o)],a=t.find(c=>c.CertificateArn?.includes(r)&&c.DomainName===n);if(a)return i(`Found existing certificate for "${n}" in "${r}.`),a.CertificateArn;if(i(`No existing certificate found for "${n}" in "${r}.`),!await Xe("Do you want to request a new certificate?"))return i(`Please add your certificate ARN to the config file in the "${Gt(o)}" setting.`),"TODO";let s=await Nn(r,n);return i("Certificate ARN: "+s),s}async function Nn(e,t){try{let r=await qe("Validate certificate using DNS or email validation?",["dns","email"],"dns"),o=new Ft({region:e}),n=new vn({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 Ln(e){let t=$t(),r=kn("rsa",{modulusLength:2048,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs1",format:"pem",cipher:"aes-256-cbc",passphrase:t}});return{keyId:(await new An({}).send(new Pn({PublicKeyConfig:{Name:e,CallerReference:$t(),EncodedKey:r.publicKey}}))).PublicKey?.Id,publicKey:r.publicKey,privateKey:r.privateKey,passphrase:t}}async function $n(e,t){let r=new xn({Name:t,WithDecryption:!0});try{return(await e.send(r)).Parameter?.Value}catch(o){if(o.name==="ParameterNotFound")return;throw o}}async function Bn(e,t,r){let o=new In({Name:t,Value:r,Type:"SecureString",Overwrite:!0});await e.send(o)}async function Fn(e,t,r){let o=new _n({region:e});for(let[n,a]of Object.entries(r)){let s=t+n,c=a.toString(),d=await $n(o,s);d!==void 0&&d!==c&&(i(`Parameter "${s}" exists with different value.`),await be(`Do you want to overwrite "${s}"?`)),await Bn(o,s,c)}}async function Vt(){let e=await ze();for(let t of e){let r=t.StackName,o=await Ve(r);o&&(we(o),console.log(""))}}import{PutObjectCommand as Gn}from"@aws-sdk/client-s3";import{ContentType as R}from"@medplum/core";import zn from"fast-glob";import{createReadStream as Vn,mkdtempSync as jn,readdirSync as qn,readFileSync as Xn,rmSync as Yn,writeFileSync as Zn}from"fs";import jt from"node-fetch";import{tmpdir as Qn}from"os";import{join as Ce,sep as ei}from"path";import{pipeline as ti}from"stream/promises";async function qt(e,t){let r=j(e);if(!r){console.log("Config not found");return}let o=await J(e);if(!o){console.log("Stack not found");return}let n=o.appBucket;if(!n){console.log("App bucket not found");return}let a=await oi("@medplum/app","latest");Xt(a,{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 ii(a,n.PhysicalResourceId,t),o.appDistribution?.PhysicalResourceId&&!t.dryrun&&await Se(o.appDistribution.PhysicalResourceId),console.log("Done")}async function ri(e,t){let r=`https://registry.npmjs.org/${e}/${t}`;return(await jt(r)).json()}async function oi(e,t){let o=(await ri(e,t)).dist.tarball,n=jn(Ce(Qn(),"tarball-"));try{let a=await jt(o),s=Rt(n);return await ti(a.body,s),Ce(n,"package","dist")}catch(a){throw Yn(n,{recursive:!0,force:!0}),a}}function Xt(e,t){for(let r of qn(e,{withFileTypes:!0})){let o=Ce(e,r.name);r.isDirectory()?Xt(o,t):r.isFile()&&o.endsWith(".js")&&ni(o,t)}}function ni(e,t){let r=Xn(e,"utf-8");for(let[o,n]of Object.entries(t))r=r.replaceAll(`__${o}__`,n);Zn(e,r)}async function ii(e,t,r){let o=[["assets/**/*.css",R.CSS,!0],["assets/**/*.css.map",R.JSON,!0],["assets/**/*.js",R.JAVASCRIPT,!0],["assets/**/*.js.map",R.JSON,!0],["assets/**/*.txt",R.TEXT,!0],["assets/**/*.ico",R.FAVICON,!0],["img/**/*.png",R.PNG,!0],["img/**/*.svg",R.SVG,!0],["robots.txt",R.TEXT,!0],["index.html",R.HTML,!1]];for(let n of o)await ai({rootDir:e,bucketName:t,fileNamePattern:n[0],contentType:n[1],cached:n[2],dryrun:r.dryrun})}async function ai(e){let t=zn.sync(e.fileNamePattern,{cwd:e.rootDir});for(let r of t)await si(Ce(e.rootDir,r),e)}async function si(e,t){let r=Vn(e),o=e.substring(t.rootDir.length+1).split(ei).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 re.send(new Gn(n))}import{GetBucketPolicyCommand as ci,PutBucketPolicyCommand as di}from"@aws-sdk/client-s3";async function Zt(e,t){if(!j(e)){console.log("Config not found");return}let o=await J(e);if(!o){console.log("Stack not found");return}await Yt("App",o.appBucket,o.appDistribution,o.appOriginAccessIdentity,t),await Yt("Storage",o.storageBucket,o.storageDistribution,o.storageOriginAccessIdentity,t),console.log("Done")}async function Yt(e,t,r,o,n){if(!t?.PhysicalResourceId){console.log(`${e} bucket not found`);return}if(!r?.PhysicalResourceId){console.log(`${e} distribution not found`);return}if(!o?.PhysicalResourceId){console.log(`${e} OAI not found`);return}let a=t.PhysicalResourceId,s=o.PhysicalResourceId,c=await pi(a);if(li(c,a,s)){console.log(`${e} bucket already has policy statement`);return}ui(c,a,s),console.log(`${e} bucket policy:`),console.log(JSON.stringify(c,void 0,2)),n.dryrun?console.log("Dry run - skipping updates"):(console.log("Updating bucket policy..."),await mi(a,c),console.log("Bucket policy updated"),console.log("Creating CloudFront invalidation..."),await Se(r.PhysicalResourceId),console.log("CloudFront invalidation created"),console.log(`${e} bucket policy updated`))}async function pi(e){let t=await re.send(new ci({Bucket:e}));return JSON.parse(t.Policy??"{}")}async function mi(e,t){await re.send(new di({Bucket:e,Policy:JSON.stringify(t)}))}function li(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 ui(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}/*`]})}import{UpdateServiceCommand as fi}from"@aws-sdk/client-ecs";async function Qt(e){let t=await J(e);if(!t){console.log("Stack not found");return}let r=t.ecsCluster?.PhysicalResourceId;if(!r){console.log("ECS Cluster not found");return}let o=je(t.ecsService);if(!o){console.log("ECS Service not found");return}await Nt.send(new fi({cluster:r,service:o,forceNewDeployment:!0})),console.log(`Service "${o}" updated successfully.`)}var U=new hi("aws").description("Commands to manage AWS resources");U.command("init").description("Initialize a new Medplum AWS CloudFormation stacks").action(zt);U.command("list").description("List Medplum AWS CloudFormation stacks").action(Vt);U.command("describe").description("Describe a Medplum AWS CloudFormation stack by tag").argument("<tag>").action(Lt);U.command("update-server").alias("deploy-server").description("Update the server image").argument("<tag>").action(Qt);U.command("update-app").alias("deploy-app").description("Update the app site").argument("<tag>").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(qt);U.command("update-bucket-policies").description("Update S3 bucket policies").argument("<tag>").option("--dryrun","Displays the operations that would be performed using the specified command without actually running them.").action(Zt);import{Command as yi}from"commander";var er=m("save"),tr=m("deploy"),rr=m("create"),or=new yi("bot").addCommand(er).addCommand(tr).addCommand(rr),Ye=m("save-bot"),Ze=m("deploy-bot"),Qe=m("create-bot");er.description("Saving the bot").argument("<botName>").action(async(e,t)=>{let r=await l(t);await ve(r,e)});tr.description("Deploy the app to AWS").argument("<botName>").action(async(e,t)=>{let r=await l(t);await ve(r,e,!0)});rr.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creating a bot").option("-runtime-version <runtimeVersion>","Runtime version (awslambda, vmcontext)").action(async(e,t,r,o,n)=>{let a=await l(n);await Ne(a,e,t,r,o,n.runtimeVersion)});async function ve(e,t,r=!1){let o=kt(t);for(let n of o){let a=await e.readResource("Bot",n.id);await Je(e,n,a),r&&await Ue(e,n,a)}console.log(`Number of bots deployed: ${o.length}`)}Ye.description("Saves the bot").argument("<botName>").action(async(e,t)=>{let r=await l(t);await ve(r,e)});Ze.description("Deploy the bot to AWS").argument("<botName>").action(async(e,t)=>{let r=await l(t);await ve(r,e,!0)});Qe.arguments("<botName> <projectId> <sourceFile> <distFile>").description("Creates and saves the bot").action(async(e,t,r,o,n)=>{let a=await l(n);await Ne(a,e,t,r,o)});import{Command as gi}from"commander";import{createReadStream as wi,writeFile as Si}from"fs";import{resolve as ir}from"path";import{createInterface as bi}from"readline";var ar=m("export"),sr=m("import"),cr=new gi("bulk").addCommand(ar).addCommand(sr);ar.option("-e, --export-level <exportLevel>",'Optional export level. Defaults to system level export. "Group/:id" - Group of Patients, "Patient" - All Patients.').option("-t, --types <types>","optional resource types to export").option("-s, --since <since>","optional Resources will be included in the response if their state has changed after the supplied time (e.g. if Resource.meta.lastUpdated is later than the supplied _since time).").option("-d, --target-directory <targetDirectory>","optional target directory to save files from the bulk export operations.").action(async e=>{let{exportLevel:t,types:r,since:o,targetDirectory:n}=e,a=await l(e);(await a.bulkExport(t,r,o)).output?.forEach(async({type:c,url:d})=>{let u=new URL(d),K=await a.download(d),k=`${c}_${u.pathname}`.replace(/[^a-zA-Z0-9]+/g,"_")+".ndjson",_=ir(n??"",k);Si(`${_}`,await K.text(),()=>{console.log(`${_} is created`)})})});sr.argument("<filename>","File Name").option("--num-resources-per-request <numResourcesPerRequest>","optional number of resources to import per batch request. Defaults to 25.","25").option("--add-extensions-for-missing-values","optional flag to add extensions for missing values in a resource",!1).option("-d, --target-directory <targetDirectory>","optional target directory of file to be imported").action(async(e,t)=>{let{numResourcesPerRequest:r,addExtensionsForMissingValues:o,targetDirectory:n}=t,a=ir(n??process.cwd(),e),s=await l(t);await Ei(a,parseInt(r,10),s,o)});async function Ei(e,t,r,o){let n=[],a=wi(e),s=bi({input:a});for await(let c of s){let d=Ci(c,o);n.push({resource:d,request:{method:"POST",url:d.resourceType}}),n.length%t===0&&(await nr(n,r),n=[])}n.length>0&&await nr(n,r)}async function nr(e,t){(await t.executeBatch({resourceType:"Bundle",type:"transaction",entry:e})).entry?.forEach(o=>{H(o.response)})}function Ci(e,t){let r=JSON.parse(e);return t?vi(r):r}function vi(e){return e.resourceType==="ExplanationOfBenefit"?Ai(e):e}function Ai(e){return e.provider||(e.provider=$e()),e.item?.forEach(t=>{t?.productOrService||(t.productOrService=$e())}),e}import{Command as Pi,Option as xi}from"commander";var dr=m("list"),pr=m("current"),mr=m("switch"),lr=m("invite"),ur=new Pi("project").addCommand(dr).addCommand(pr).addCommand(mr).addCommand(lr);dr.description("List of current projects").action(async e=>{let t=await l(e);Ii(t)});function Ii(e){let r=e.getLogins().map(o=>`${o.project.display} (${o.project.reference})`).join(`
|
|
6
6
|
|
|
7
|
-
`);console.log(r)}
|
|
8
|
-
`)):console.log(`Error: project ${t} not found. Make sure you are added as a user to this project`)}async function
|
|
7
|
+
`);console.log(r)}pr.description("Project you are currently on").action(async e=>{let r=(await l(e)).getActiveLogin();if(!r)throw new Error("Unauthenticated: run `npx medplum login` to login");console.log(`${r.project.display} (${r.project.reference})`)});mr.description("Switching to another project from the current one").argument("<projectId>").action(async(e,t)=>{let r=await l(t);await _i(r,e)});lr.description("Invite a member to your current project (run npx medplum project current to confirm)").arguments("<firstName> <lastName> <email>").option("--send-email","If you want to send the email when inviting the user").option("--admin","If the user you are inviting is an admin").addOption(new xi("-r, --role <role>","Role of user").choices(["Practitioner","Patient","RelatedPerson"]).default("Practitioner")).action(async(e,t,r,o)=>{let n=await l(o),a=n.getActiveLogin();if(!a)throw new Error("Unauthenticated: run `npx medplum login` to login");if(!a.project.reference)throw new Error("No current project to invite user to");let s=a.project.reference.split("/")[1],c={resourceType:o.role,firstName:e,lastName:t,email:r,sendEmail:!!o.sendEmail,admin:!!o.admin};await Ti(s,c,n)});async function _i(e,t){let o=e.getLogins().find(n=>n.project.reference?.includes(t));o?(await e.setActiveLogin(o),console.log(`Switched to project ${t}
|
|
8
|
+
`)):console.log(`Error: project ${t} not found. Make sure you are added as a user to this project`)}async function Ti(e,t,r){try{await r.invite(e,t),t.sendEmail&&console.log("Email sent"),console.log("See your users at https://app.medplum.com/admin/users")}catch(o){console.log("Error while sending invite "+o)}}import{convertToTransactionBundle as Ki}from"@medplum/core";var et=m("delete"),tt=m("get"),rt=m("patch"),ot=m("post"),nt=m("put");et.argument("<url>","Resource/$id").action(async(e,t)=>{let r=await l(t);H(await r.delete(ne(r,e)))});tt.argument("<url>","Resource/$id").option("--as-transaction","Print out the bundle as a transaction type").action(async(e,t)=>{let r=await l(t),o=await r.get(ne(r,e));t.asTransaction?H(Ki(o)):H(o)});rt.arguments("<url> <body>").action(async(e,t,r)=>{let o=await l(r);H(await o.patch(ne(o,e),it(t)))});ot.arguments("<url> <body>").action(async(e,t,r)=>{let o=await l(r);H(await o.post(ne(o,e),it(t)))});nt.arguments("<url> <body>").action(async(e,t,r)=>{let o=await l(r);H(await o.put(ne(o,e),it(t)))});function it(e){if(e)try{return JSON.parse(e)}catch{return e}}function ne(e,t){return["admin/","auth/","fhir/R4"].some(o=>t.startsWith(o))?t:e.fhirUrl(t).toString()}import{Command as ki}from"commander";import{resolve as Ri}from"path";import{readdirSync as Oi}from"fs";import{homedir as Hi}from"os";var fr=m("set"),hr=m("remove"),yr=m("list"),gr=m("describe"),wr=new ki("profile").addCommand(fr).addCommand(hr).addCommand(yr).addCommand(gr);fr.argument("<profileName>","Name of the profile").description("Create a new profile or replace it with the given name and its associated properties").action(async(e,t)=>{he(e,t)});hr.argument("<profileName>","Name of the profile").description("Remove a profile by name").action(async e=>{new I(e).setObject("options",void 0),console.log(`${e} profile removed`)});yr.description("List all profiles saved").action(async()=>{let e=Ri(Hi(),".medplum"),t=Oi(e),r=[];t.forEach(o=>{let n=o.split(".")[0],s=new I(n).getObject("options");s&&r.push({profileName:n,profile:s})}),console.log(r)});gr.argument("<profileName>","Name of the profile").description("Describes a profile").action(async e=>{let t=ye(e);console.log(t)});async function Ui(e){try{let t=new Di("medplum").description("Command to access Medplum CLI");t.version(Wi),t.addCommand(Fe),t.addCommand(Ge),t.addCommand(tt),t.addCommand(ot),t.addCommand(rt),t.addCommand(nt),t.addCommand(et),t.addCommand(ur),t.addCommand(cr),t.addCommand(or),t.addCommand(Ye),t.addCommand(Ze),t.addCommand(Qe),t.addCommand(wr),t.addCommand(U),await t.parseAsync(e)}catch(t){console.error("Error: "+Mi(t))}}async function Ni(){Ji.config(),await Ui(process.argv)}at.main===module&&Ni().catch(e=>console.error("Unhandled error:",e));export{Ui as main,Ni as run};
|
|
9
9
|
//# sourceMappingURL=index.mjs.map
|