@rockcarver/frodo-lib 2.0.0-3 → 2.0.0-4

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.
Files changed (149) hide show
  1. package/CHANGELOG.md +5 -1
  2. package/cjs/api/AgentApi.js +64 -16
  3. package/cjs/api/AgentApi.js.map +1 -1
  4. package/cjs/api/ApiTypes.js +0 -55
  5. package/cjs/api/ApiTypes.js.map +1 -1
  6. package/cjs/api/BaseApi.js +21 -11
  7. package/cjs/api/BaseApi.js.map +1 -1
  8. package/cjs/api/cloud/SecretsApi.js +7 -14
  9. package/cjs/api/cloud/SecretsApi.js.map +1 -1
  10. package/cjs/api/cloud/SecretsApi.test.js.map +1 -1
  11. package/cjs/ops/AdminOps.js +254 -60
  12. package/cjs/ops/AdminOps.js.map +1 -1
  13. package/cjs/ops/AgentOps.js +352 -108
  14. package/cjs/ops/AgentOps.js.map +1 -1
  15. package/cjs/ops/AuthenticateOps.js +253 -60
  16. package/cjs/ops/AuthenticateOps.js.map +1 -1
  17. package/cjs/ops/CirclesOfTrustOps.js +16 -4
  18. package/cjs/ops/CirclesOfTrustOps.js.map +1 -1
  19. package/cjs/ops/ConnectionProfileOps.js +163 -40
  20. package/cjs/ops/ConnectionProfileOps.js.map +1 -1
  21. package/cjs/ops/EmailTemplateOps.js +7 -1
  22. package/cjs/ops/EmailTemplateOps.js.map +1 -1
  23. package/cjs/ops/IdpOps.js +55 -12
  24. package/cjs/ops/IdpOps.js.map +1 -1
  25. package/cjs/ops/JourneyOps.js +645 -136
  26. package/cjs/ops/JourneyOps.js.map +1 -1
  27. package/cjs/ops/NodeOps.js +96 -24
  28. package/cjs/ops/NodeOps.js.map +1 -1
  29. package/cjs/ops/OAuth2ClientOps.js +45 -11
  30. package/cjs/ops/OAuth2ClientOps.js.map +1 -1
  31. package/cjs/ops/OpsTypes.js +0 -23
  32. package/cjs/ops/OpsTypes.js.map +1 -1
  33. package/cjs/ops/OrganizationOps.js +44 -10
  34. package/cjs/ops/OrganizationOps.js.map +1 -1
  35. package/cjs/ops/PolicyOps.js +86 -24
  36. package/cjs/ops/PolicyOps.js.map +1 -1
  37. package/cjs/ops/PolicySetOps.js +72 -18
  38. package/cjs/ops/PolicySetOps.js.map +1 -1
  39. package/cjs/ops/ResourceTypeOps.js +24 -6
  40. package/cjs/ops/ResourceTypeOps.js.map +1 -1
  41. package/cjs/ops/Saml2Ops.js +120 -33
  42. package/cjs/ops/Saml2Ops.js.map +1 -1
  43. package/cjs/ops/Saml2Ops.test.js.map +1 -1
  44. package/cjs/ops/ScriptOps.js +73 -17
  45. package/cjs/ops/ScriptOps.js.map +1 -1
  46. package/cjs/ops/ServiceOps.js +152 -35
  47. package/cjs/ops/ServiceOps.js.map +1 -1
  48. package/cjs/ops/ThemeOps.js +20 -5
  49. package/cjs/ops/ThemeOps.js.map +1 -1
  50. package/cjs/ops/cloud/FeatureOps.js +4 -1
  51. package/cjs/ops/cloud/FeatureOps.js.map +1 -1
  52. package/cjs/ops/cloud/SecretsOps.js.map +1 -1
  53. package/cjs/ops/cloud/ServiceAccountOps.js +24 -6
  54. package/cjs/ops/cloud/ServiceAccountOps.js.map +1 -1
  55. package/cjs/ops/cloud/StartupOps.js +55 -11
  56. package/cjs/ops/cloud/StartupOps.js.map +1 -1
  57. package/cjs/ops/utils/Console.js +47 -22
  58. package/cjs/ops/utils/Console.js.map +1 -1
  59. package/cjs/ops/utils/DataProtection.js +12 -5
  60. package/cjs/ops/utils/DataProtection.js.map +1 -1
  61. package/cjs/ops/utils/DataProtection.test.js.map +1 -1
  62. package/cjs/ops/utils/ExportImportUtils.js +15 -8
  63. package/cjs/ops/utils/ExportImportUtils.js.map +1 -1
  64. package/cjs/ops/utils/ScriptValidationUtils.js +33 -8
  65. package/cjs/ops/utils/ScriptValidationUtils.js.map +1 -1
  66. package/cjs/ops/utils/ScriptValidationUtils.test.js.map +1 -1
  67. package/cjs/utils/SetupPollyForFrodoLib.js +67 -19
  68. package/cjs/utils/SetupPollyForFrodoLib.js.map +1 -1
  69. package/esm/api/AgentApi.mjs +64 -16
  70. package/esm/api/ApiTypes.mjs +1 -50
  71. package/esm/api/BaseApi.mjs +21 -11
  72. package/esm/api/cloud/SecretsApi.mjs +0 -5
  73. package/esm/api/cloud/SecretsApi.test.mjs +3 -3
  74. package/esm/ops/AdminOps.mjs +254 -60
  75. package/esm/ops/AgentOps.mjs +352 -104
  76. package/esm/ops/AuthenticateOps.mjs +253 -60
  77. package/esm/ops/CirclesOfTrustOps.mjs +16 -4
  78. package/esm/ops/ConnectionProfileOps.mjs +163 -40
  79. package/esm/ops/EmailTemplateOps.mjs +5 -0
  80. package/esm/ops/IdpOps.mjs +55 -12
  81. package/esm/ops/JourneyOps.mjs +639 -132
  82. package/esm/ops/NodeOps.mjs +90 -19
  83. package/esm/ops/OAuth2ClientOps.mjs +45 -11
  84. package/esm/ops/OpsTypes.mjs +1 -22
  85. package/esm/ops/OrganizationOps.mjs +44 -10
  86. package/esm/ops/PolicyOps.mjs +86 -24
  87. package/esm/ops/PolicySetOps.mjs +72 -18
  88. package/esm/ops/ResourceTypeOps.mjs +24 -6
  89. package/esm/ops/Saml2Ops.mjs +120 -33
  90. package/esm/ops/Saml2Ops.test.mjs +10 -11
  91. package/esm/ops/ScriptOps.mjs +73 -17
  92. package/esm/ops/ServiceOps.mjs +152 -35
  93. package/esm/ops/ThemeOps.mjs +20 -5
  94. package/esm/ops/cloud/FeatureOps.mjs +4 -1
  95. package/esm/ops/cloud/ServiceAccountOps.mjs +24 -6
  96. package/esm/ops/cloud/StartupOps.mjs +55 -11
  97. package/esm/ops/utils/Console.mjs +33 -9
  98. package/esm/ops/utils/DataProtection.mjs +9 -2
  99. package/esm/ops/utils/DataProtection.test.mjs +8 -2
  100. package/esm/ops/utils/ExportImportUtils.mjs +15 -8
  101. package/esm/ops/utils/ScriptValidationUtils.mjs +30 -8
  102. package/esm/ops/utils/ScriptValidationUtils.test.mjs +14 -3
  103. package/esm/utils/SetupPollyForFrodoLib.mjs +64 -18
  104. package/package.json +1 -1
  105. package/types/api/AgentApi.d.ts +6 -6
  106. package/types/api/AgentApi.d.ts.map +1 -1
  107. package/types/api/ApiTypes.d.ts +12 -49
  108. package/types/api/ApiTypes.d.ts.map +1 -1
  109. package/types/api/BaseApi.d.ts.map +1 -1
  110. package/types/api/cloud/SecretsApi.d.ts +1 -4
  111. package/types/api/cloud/SecretsApi.d.ts.map +1 -1
  112. package/types/ops/AdminOps.d.ts.map +1 -1
  113. package/types/ops/AgentOps.d.ts +3 -6
  114. package/types/ops/AgentOps.d.ts.map +1 -1
  115. package/types/ops/AuthenticateOps.d.ts.map +1 -1
  116. package/types/ops/CirclesOfTrustOps.d.ts.map +1 -1
  117. package/types/ops/ConnectionProfileOps.d.ts.map +1 -1
  118. package/types/ops/EmailTemplateOps.d.ts +4 -0
  119. package/types/ops/EmailTemplateOps.d.ts.map +1 -1
  120. package/types/ops/IdpOps.d.ts.map +1 -1
  121. package/types/ops/JourneyOps.d.ts +10 -4
  122. package/types/ops/JourneyOps.d.ts.map +1 -1
  123. package/types/ops/NodeOps.d.ts +10 -4
  124. package/types/ops/NodeOps.d.ts.map +1 -1
  125. package/types/ops/OAuth2ClientOps.d.ts.map +1 -1
  126. package/types/ops/OpsTypes.d.ts +2 -12
  127. package/types/ops/OpsTypes.d.ts.map +1 -1
  128. package/types/ops/OrganizationOps.d.ts.map +1 -1
  129. package/types/ops/PolicyOps.d.ts.map +1 -1
  130. package/types/ops/PolicySetOps.d.ts.map +1 -1
  131. package/types/ops/ResourceTypeOps.d.ts.map +1 -1
  132. package/types/ops/Saml2Ops.d.ts.map +1 -1
  133. package/types/ops/ScriptOps.d.ts.map +1 -1
  134. package/types/ops/ServiceOps.d.ts.map +1 -1
  135. package/types/ops/ThemeOps.d.ts.map +1 -1
  136. package/types/ops/cloud/FeatureOps.d.ts.map +1 -1
  137. package/types/ops/cloud/SecretsOps.d.ts +1 -1
  138. package/types/ops/cloud/SecretsOps.d.ts.map +1 -1
  139. package/types/ops/cloud/ServiceAccountOps.d.ts.map +1 -1
  140. package/types/ops/cloud/StartupOps.d.ts.map +1 -1
  141. package/types/ops/utils/Console.d.ts +34 -7
  142. package/types/ops/utils/Console.d.ts.map +1 -1
  143. package/types/ops/utils/DataProtection.d.ts +5 -1
  144. package/types/ops/utils/DataProtection.d.ts.map +1 -1
  145. package/types/ops/utils/ExportImportUtils.d.ts.map +1 -1
  146. package/types/ops/utils/ScriptValidationUtils.d.ts +14 -4
  147. package/types/ops/utils/ScriptValidationUtils.d.ts.map +1 -1
  148. package/types/utils/SetupPollyForFrodoLib.d.ts +5 -1
  149. package/types/utils/SetupPollyForFrodoLib.d.ts.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ops/NodeOps.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,iBAAiB,CAAC;AAcpC,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAE/C,MAAM,CAAC,OAAO,OAAO,OAAO;IAC1B,KAAK,EAAE,KAAK,CAAC;gBACD,KAAK,EAAE,KAAK;IAIxB;;;OAGG;IACG,iBAAiB,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;IAI7C;;;;OAIG;IACG,mBAAmB,CACvB,aAAa,EAAE,YAAY,EAAE,GAC5B,OAAO,CAAC,YAAY,EAAE,CAAC;IAI1B;;;;OAIG;IACH,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO;IAIxC;;;;OAIG;IACH,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO;IAI1C;;;;OAIG;IACH,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO;IAIvC;;;;;;;OAOG;IACH,qBAAqB,CAAC,QAAQ,EAAE,MAAM,GAAG,kBAAkB,EAAE;CAG9D;AAID;;;GAGG;AACH,wBAAsB,iBAAiB,CAAC,EACtC,KAAK,GACN,EAAE;IACD,KAAK,EAAE,KAAK,CAAC;CACd,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC,CAqFrB;AAED;;;;GAIG;AACH,wBAAsB,mBAAmB,CAAC,EACxC,aAAa,EACb,KAAK,GACN,EAAE;IACD,aAAa,EAAE,YAAY,EAAE,CAAC;IAC9B,KAAK,EAAE,KAAK,CAAC;CACd,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC,CAkB1B;AAsOD;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAEvD;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAEzD;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,EAC3B,QAAQ,EACR,KAAK,GACN,EAAE;IACD,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,KAAK,CAAC;CACd,GAAG,OAAO,CA6CV;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,EACpC,QAAQ,EACR,KAAK,GACN,EAAE;IACD,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,KAAK,CAAC;CACd,GAAG,kBAAkB,EAAE,CAcvB","file":"NodeOps.d.ts","sourcesContent":["import State from '../shared/State';\nimport {\n getNode,\n deleteNode,\n getNodeTypes,\n getNodesByType,\n} from '../api/NodeApi';\nimport { getTrees } from '../api/TreeApi';\nimport {\n printMessage,\n createProgressIndicator,\n updateProgressIndicator,\n stopProgressIndicator,\n} from './utils/Console';\nimport { NodeClassification } from './OpsTypes';\nimport { NodeSkeleton } from '../api/ApiTypes';\n\nexport default class NodeOps {\n state: State;\n constructor(state: State) {\n this.state = state;\n }\n\n /**\n * Find all node configuration objects that are no longer referenced by any tree\n * @returns {Promise<unknown[]>} a promise that resolves to an array of orphaned nodes\n */\n async findOrphanedNodes(): Promise<unknown[]> {\n return findOrphanedNodes({ state: this.state });\n }\n\n /**\n * Remove orphaned nodes\n * @param {NodeSkeleton[]} orphanedNodes Pass in an array of orphaned node configuration objects to remove\n * @returns {Promise<NodeSkeleton[]>} a promise that resolves to an array nodes that encountered errors deleting\n */\n async removeOrphanedNodes(\n orphanedNodes: NodeSkeleton[]\n ): Promise<NodeSkeleton[]> {\n return removeOrphanedNodes({ orphanedNodes, state: this.state });\n }\n\n /**\n * Analyze if a node is a premium node.\n * @param {string} nodeType Node type\n * @returns {boolean} True if the node type is premium, false otherwise.\n */\n isPremiumNode(nodeType: string): boolean {\n return isPremiumNode(nodeType);\n }\n\n /**\n * Analyze if a node is a cloud-only node.\n * @param {string} nodeType Node type\n * @returns {boolean} True if the node type is cloud-only, false otherwise.\n */\n isCloudOnlyNode(nodeType: string): boolean {\n return isCloudOnlyNode(nodeType);\n }\n\n /**\n * Analyze if a node is custom.\n * @param {string} nodeType Node type\n * @returns {boolean} True if the node type is custom, false otherwise.\n */\n isCustomNode(nodeType: string): boolean {\n return isCustomNode({ nodeType, state: this.state });\n }\n\n /**\n * Get a node's classifications, which can be one or multiple of:\n * - standard: can run on any instance of a ForgeRock platform\n * - cloud: utilize nodes, which are exclusively available in the ForgeRock Identity Cloud\n * - premium: utilizes nodes, which come at a premium\n * @param {string} nodeType Node type\n * @returns {NodeClassification[]} an array of one or multiple classifications\n */\n getNodeClassification(nodeType: string): NodeClassification[] {\n return getNodeClassification({ nodeType, state: this.state });\n }\n}\n\nconst containerNodes = ['PageNode', 'CustomPageNode'];\n\n/**\n * Find all node configuration objects that are no longer referenced by any tree\n * @returns {Promise<unknown[]>} a promise that resolves to an array of orphaned nodes\n */\nexport async function findOrphanedNodes({\n state,\n}: {\n state: State;\n}): Promise<unknown[]> {\n const allNodes = [];\n const orphanedNodes = [];\n let types = [];\n const allJourneys = (await getTrees({ state })).result;\n let errorMessage = '';\n const errorTypes = [];\n\n createProgressIndicator(\n undefined,\n `Counting total nodes...`,\n 'indeterminate'\n );\n try {\n types = (await getNodeTypes({ state })).result;\n } catch (error) {\n printMessage('Error retrieving all available node types:', 'error');\n printMessage(error.response.data, 'error');\n return [];\n }\n for (const type of types) {\n try {\n // eslint-disable-next-line no-await-in-loop, no-loop-func\n const nodes = (await getNodesByType({ nodeType: type._id, state }))\n .result;\n for (const node of nodes) {\n allNodes.push(node);\n updateProgressIndicator(\n `${allNodes.length} total nodes${errorMessage}`\n );\n }\n } catch (error) {\n errorTypes.push(type._id);\n errorMessage = ` (Skipped type(s): ${errorTypes})`['yellow'];\n updateProgressIndicator(`${allNodes.length} total nodes${errorMessage}`);\n }\n }\n if (errorTypes.length > 0) {\n stopProgressIndicator(\n `${allNodes.length} total nodes${errorMessage}`,\n 'warn'\n );\n } else {\n stopProgressIndicator(`${allNodes.length} total nodes`, 'success');\n }\n\n createProgressIndicator(\n undefined,\n 'Counting active nodes...',\n 'indeterminate'\n );\n const activeNodes = [];\n for (const journey of allJourneys) {\n for (const nodeId in journey.nodes) {\n if ({}.hasOwnProperty.call(journey.nodes, nodeId)) {\n activeNodes.push(nodeId);\n updateProgressIndicator(`${activeNodes.length} active nodes`);\n const node = journey.nodes[nodeId];\n if (containerNodes.includes(node.nodeType)) {\n const containerNode = await getNode({\n nodeId,\n nodeType: node.nodeType,\n state,\n });\n for (const innerNode of containerNode.nodes) {\n activeNodes.push(innerNode._id);\n updateProgressIndicator(`${activeNodes.length} active nodes`);\n }\n }\n }\n }\n }\n stopProgressIndicator(`${activeNodes.length} active nodes`, 'success');\n\n createProgressIndicator(\n undefined,\n 'Calculating orphaned nodes...',\n 'indeterminate'\n );\n const diff = allNodes.filter((x) => !activeNodes.includes(x._id));\n for (const orphanedNode of diff) {\n orphanedNodes.push(orphanedNode);\n }\n stopProgressIndicator(`${orphanedNodes.length} orphaned nodes`, 'success');\n return orphanedNodes;\n}\n\n/**\n * Remove orphaned nodes\n * @param {NodeSkeleton[]} orphanedNodes Pass in an array of orphaned node configuration objects to remove\n * @returns {Promise<NodeSkeleton[]>} a promise that resolves to an array nodes that encountered errors deleting\n */\nexport async function removeOrphanedNodes({\n orphanedNodes,\n state,\n}: {\n orphanedNodes: NodeSkeleton[];\n state: State;\n}): Promise<NodeSkeleton[]> {\n const errorNodes = [];\n createProgressIndicator(orphanedNodes.length, 'Removing orphaned nodes...');\n for (const node of orphanedNodes) {\n updateProgressIndicator(`Removing ${node['_id']}...`);\n try {\n await deleteNode({\n nodeId: node['_id'],\n nodeType: node['_type']['_id'],\n state,\n });\n } catch (deleteError) {\n errorNodes.push(node);\n printMessage(` ${deleteError}`, 'error');\n }\n }\n stopProgressIndicator(`Removed ${orphanedNodes.length} orphaned nodes.`);\n return errorNodes;\n}\n\nconst OOTB_NODE_TYPES_7 = [\n 'AcceptTermsAndConditionsNode',\n 'AccountActiveDecisionNode',\n 'AccountLockoutNode',\n 'AgentDataStoreDecisionNode',\n 'AnonymousSessionUpgradeNode',\n 'AnonymousUserNode',\n 'AttributeCollectorNode',\n 'AttributePresentDecisionNode',\n 'AttributeValueDecisionNode',\n 'AuthLevelDecisionNode',\n 'ChoiceCollectorNode',\n 'ConsentNode',\n 'CookiePresenceDecisionNode',\n 'CreateObjectNode',\n 'CreatePasswordNode',\n 'DataStoreDecisionNode',\n 'DeviceGeoFencingNode',\n 'DeviceLocationMatchNode',\n 'DeviceMatchNode',\n 'DeviceProfileCollectorNode',\n 'DeviceSaveNode',\n 'DeviceTamperingVerificationNode',\n 'DisplayUserNameNode',\n 'EmailSuspendNode',\n 'EmailTemplateNode',\n 'IdentifyExistingUserNode',\n 'IncrementLoginCountNode',\n 'InnerTreeEvaluatorNode',\n 'IotAuthenticationNode',\n 'IotRegistrationNode',\n 'KbaCreateNode',\n 'KbaDecisionNode',\n 'KbaVerifyNode',\n 'LdapDecisionNode',\n 'LoginCountDecisionNode',\n 'MessageNode',\n 'MetadataNode',\n 'MeterNode',\n 'ModifyAuthLevelNode',\n 'OneTimePasswordCollectorDecisionNode',\n 'OneTimePasswordGeneratorNode',\n 'OneTimePasswordSmsSenderNode',\n 'OneTimePasswordSmtpSenderNode',\n 'PageNode',\n 'PasswordCollectorNode',\n 'PatchObjectNode',\n 'PersistentCookieDecisionNode',\n 'PollingWaitNode',\n 'ProfileCompletenessDecisionNode',\n 'ProvisionDynamicAccountNode',\n 'ProvisionIdmAccountNode',\n 'PushAuthenticationSenderNode',\n 'PushResultVerifierNode',\n 'QueryFilterDecisionNode',\n 'RecoveryCodeCollectorDecisionNode',\n 'RecoveryCodeDisplayNode',\n 'RegisterLogoutWebhookNode',\n 'RemoveSessionPropertiesNode',\n 'RequiredAttributesDecisionNode',\n 'RetryLimitDecisionNode',\n 'ScriptedDecisionNode',\n 'SelectIdPNode',\n 'SessionDataNode',\n 'SetFailureUrlNode',\n 'SetPersistentCookieNode',\n 'SetSessionPropertiesNode',\n 'SetSuccessUrlNode',\n 'SocialFacebookNode',\n 'SocialGoogleNode',\n 'SocialNode',\n 'SocialOAuthIgnoreProfileNode',\n 'SocialOpenIdConnectNode',\n 'SocialProviderHandlerNode',\n 'TermsAndConditionsDecisionNode',\n 'TimeSinceDecisionNode',\n 'TimerStartNode',\n 'TimerStopNode',\n 'UsernameCollectorNode',\n 'ValidatedPasswordNode',\n 'ValidatedUsernameNode',\n 'WebAuthnAuthenticationNode',\n 'WebAuthnDeviceStorageNode',\n 'WebAuthnRegistrationNode',\n 'ZeroPageLoginNode',\n 'product-CertificateCollectorNode',\n 'product-CertificateUserExtractorNode',\n 'product-CertificateValidationNode',\n 'product-KerberosNode',\n 'product-ReCaptchaNode',\n 'product-Saml2Node',\n 'product-WriteFederationInformationNode',\n];\n\nconst OOTB_NODE_TYPES_7_1 = [\n 'PushRegistrationNode',\n 'GetAuthenticatorAppNode',\n 'MultiFactorRegistrationOptionsNode',\n 'OptOutMultiFactorAuthenticationNode',\n].concat(OOTB_NODE_TYPES_7);\n\nconst OOTB_NODE_TYPES_7_2 = [\n 'OathRegistrationNode',\n 'OathTokenVerifierNode',\n 'PassthroughAuthenticationNode',\n 'ConfigProviderNode',\n 'DebugNode',\n].concat(OOTB_NODE_TYPES_7_1);\n\nconst OOTB_NODE_TYPES_7_3 = [].concat(OOTB_NODE_TYPES_7_2);\n\nconst OOTB_NODE_TYPES_6_5 = [\n 'AbstractSocialAuthLoginNode',\n 'AccountLockoutNode',\n 'AgentDataStoreDecisionNode',\n 'AnonymousUserNode',\n 'AuthLevelDecisionNode',\n 'ChoiceCollectorNode',\n 'CookiePresenceDecisionNode',\n 'CreatePasswordNode',\n 'DataStoreDecisionNode',\n 'InnerTreeEvaluatorNode',\n 'LdapDecisionNode',\n 'MessageNode',\n 'MetadataNode',\n 'MeterNode',\n 'ModifyAuthLevelNode',\n 'OneTimePasswordCollectorDecisionNode',\n 'OneTimePasswordGeneratorNode',\n 'OneTimePasswordSmsSenderNode',\n 'OneTimePasswordSmtpSenderNode',\n 'PageNode',\n 'PasswordCollectorNode',\n 'PersistentCookieDecisionNode',\n 'PollingWaitNode',\n 'ProvisionDynamicAccountNode',\n 'ProvisionIdmAccountNode',\n 'PushAuthenticationSenderNode',\n 'PushResultVerifierNode',\n 'RecoveryCodeCollectorDecisionNode',\n 'RecoveryCodeDisplayNode',\n 'RegisterLogoutWebhookNode',\n 'RemoveSessionPropertiesNode',\n 'RetryLimitDecisionNode',\n 'ScriptedDecisionNode',\n 'SessionDataNode',\n 'SetFailureUrlNode',\n 'SetPersistentCookieNode',\n 'SetSessionPropertiesNode',\n 'SetSuccessUrlNode',\n 'SocialFacebookNode',\n 'SocialGoogleNode',\n 'SocialNode',\n 'SocialOAuthIgnoreProfileNode',\n 'SocialOpenIdConnectNode',\n 'TimerStartNode',\n 'TimerStopNode',\n 'UsernameCollectorNode',\n 'WebAuthnAuthenticationNode',\n 'WebAuthnRegistrationNode',\n 'ZeroPageLoginNode',\n];\n\nconst OOTB_NODE_TYPES_6 = [\n 'AbstractSocialAuthLoginNode',\n 'AccountLockoutNode',\n 'AgentDataStoreDecisionNode',\n 'AnonymousUserNode',\n 'AuthLevelDecisionNode',\n 'ChoiceCollectorNode',\n 'CookiePresenceDecisionNode',\n 'CreatePasswordNode',\n 'DataStoreDecisionNode',\n 'InnerTreeEvaluatorNode',\n 'LdapDecisionNode',\n 'MessageNode',\n 'MetadataNode',\n 'MeterNode',\n 'ModifyAuthLevelNode',\n 'OneTimePasswordCollectorDecisionNode',\n 'OneTimePasswordGeneratorNode',\n 'OneTimePasswordSmsSenderNode',\n 'OneTimePasswordSmtpSenderNode',\n 'PageNode',\n 'PasswordCollectorNode',\n 'PersistentCookieDecisionNode',\n 'PollingWaitNode',\n 'ProvisionDynamicAccountNode',\n 'ProvisionIdmAccountNode',\n 'PushAuthenticationSenderNode',\n 'PushResultVerifierNode',\n 'RecoveryCodeCollectorDecisionNode',\n 'RecoveryCodeDisplayNode',\n 'RegisterLogoutWebhookNode',\n 'RemoveSessionPropertiesNode',\n 'RetryLimitDecisionNode',\n 'ScriptedDecisionNode',\n 'SessionDataNode',\n 'SetFailureUrlNode',\n 'SetPersistentCookieNode',\n 'SetSessionPropertiesNode',\n 'SetSuccessUrlNode',\n 'SocialFacebookNode',\n 'SocialGoogleNode',\n 'SocialNode',\n 'SocialOAuthIgnoreProfileNode',\n 'SocialOpenIdConnectNode',\n 'TimerStartNode',\n 'TimerStopNode',\n 'UsernameCollectorNode',\n 'WebAuthnAuthenticationNode',\n 'WebAuthnRegistrationNode',\n 'ZeroPageLoginNode',\n];\n\nconst CLOUD_ONLY_NODE_TYPES = [\n 'IdentityStoreDecisionNode',\n 'AutonomousAccessSignalNode',\n 'AutonomousAccessDecisionNode',\n 'AutonomousAccessResultNode',\n];\n\nconst PREMIUM_NODE_TYPES = [\n 'AutonomousAccessSignalNode',\n 'AutonomousAccessDecisionNode',\n 'AutonomousAccessResultNode',\n];\n\n/**\n * Analyze if a node is a premium node.\n * @param {string} nodeType Node type\n * @returns {boolean} True if the node type is premium, false otherwise.\n */\nexport function isPremiumNode(nodeType: string): boolean {\n return PREMIUM_NODE_TYPES.includes(nodeType);\n}\n\n/**\n * Analyze if a node is a cloud-only node.\n * @param {string} nodeType Node type\n * @returns {boolean} True if the node type is cloud-only, false otherwise.\n */\nexport function isCloudOnlyNode(nodeType: string): boolean {\n return CLOUD_ONLY_NODE_TYPES.includes(nodeType);\n}\n\n/**\n * Analyze if a node is custom.\n * @param {string} nodeType Node type\n * @returns {boolean} True if the node type is custom, false otherwise.\n */\nexport function isCustomNode({\n nodeType,\n state,\n}: {\n nodeType: string;\n state: State;\n}): boolean {\n let ootbNodeTypes = [];\n switch (state.getAmVersion()) {\n case '7.1.0':\n ootbNodeTypes = OOTB_NODE_TYPES_7_1.slice(0);\n break;\n case '7.2.0':\n ootbNodeTypes = OOTB_NODE_TYPES_7_2.slice(0);\n break;\n case '7.3.0':\n ootbNodeTypes = OOTB_NODE_TYPES_7_3.slice(0);\n break;\n case '7.0.0':\n case '7.0.1':\n case '7.0.2':\n ootbNodeTypes = OOTB_NODE_TYPES_7.slice(0);\n break;\n case '6.5.3':\n case '6.5.2.3':\n case '6.5.2.2':\n case '6.5.2.1':\n case '6.5.2':\n case '6.5.1':\n case '6.5.0.2':\n case '6.5.0.1':\n ootbNodeTypes = OOTB_NODE_TYPES_6_5.slice(0);\n break;\n case '6.0.0.7':\n case '6.0.0.6':\n case '6.0.0.5':\n case '6.0.0.4':\n case '6.0.0.3':\n case '6.0.0.2':\n case '6.0.0.1':\n case '6.0.0':\n ootbNodeTypes = OOTB_NODE_TYPES_6.slice(0);\n break;\n default:\n return true;\n }\n return (\n !ootbNodeTypes.includes(nodeType) &&\n !isPremiumNode(nodeType) &&\n !isCloudOnlyNode(nodeType)\n );\n}\n\n/**\n * Get a node's classifications, which can be one or multiple of:\n * - standard: can run on any instance of a ForgeRock platform\n * - cloud: utilize nodes, which are exclusively available in the ForgeRock Identity Cloud\n * - premium: utilizes nodes, which come at a premium\n * @param {string} nodeType Node type\n * @returns {NodeClassification[]} an array of one or multiple classifications\n */\nexport function getNodeClassification({\n nodeType,\n state,\n}: {\n nodeType: string;\n state: State;\n}): NodeClassification[] {\n const classifications: NodeClassification[] = [];\n const premium = isPremiumNode(nodeType);\n const custom = isCustomNode({ nodeType, state });\n const cloud = isCloudOnlyNode(nodeType);\n if (custom) {\n classifications.push(NodeClassification.CUSTOM);\n } else if (cloud) {\n classifications.push(NodeClassification.CLOUD);\n } else {\n classifications.push(NodeClassification.STANDARD);\n }\n if (premium) classifications.push(NodeClassification.PREMIUM);\n return classifications;\n}\n"]}
1
+ {"version":3,"sources":["../src/ops/NodeOps.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,iBAAiB,CAAC;AAcpC,OAAO,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AACpD,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAE/C,MAAM,CAAC,OAAO,OAAO,OAAO;IAC1B,KAAK,EAAE,KAAK,CAAC;gBACD,KAAK,EAAE,KAAK;IAIxB;;;OAGG;IACG,iBAAiB,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;IAI7C;;;;OAIG;IACG,mBAAmB,CACvB,aAAa,EAAE,YAAY,EAAE,GAC5B,OAAO,CAAC,YAAY,EAAE,CAAC;IAI1B;;;;OAIG;IACH,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO;IAIxC;;;;OAIG;IACH,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO;IAI1C;;;;OAIG;IACH,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO;IAIvC;;;;;;;OAOG;IACH,qBAAqB,CAAC,QAAQ,EAAE,MAAM,GAAG,sBAAsB,EAAE;CAGlE;AAED,oBAAY,kBAAkB;IAC5B,QAAQ,aAAa;IACrB,MAAM,WAAW;IACjB,KAAK,UAAU;IACf,OAAO,YAAY;CACpB;AAID;;;GAGG;AACH,wBAAsB,iBAAiB,CAAC,EACtC,KAAK,GACN,EAAE;IACD,KAAK,EAAE,KAAK,CAAC;CACd,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC,CAmHrB;AAED;;;;GAIG;AACH,wBAAsB,mBAAmB,CAAC,EACxC,aAAa,EACb,KAAK,GACN,EAAE;IACD,aAAa,EAAE,YAAY,EAAE,CAAC;IAC9B,KAAK,EAAE,KAAK,CAAC;CACd,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC,CAyB1B;AAsOD;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAEvD;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAEzD;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,EAC3B,QAAQ,EACR,KAAK,GACN,EAAE;IACD,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,KAAK,CAAC;CACd,GAAG,OAAO,CA6CV;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CAAC,EACpC,QAAQ,EACR,KAAK,GACN,EAAE;IACD,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,KAAK,CAAC;CACd,GAAG,sBAAsB,EAAE,CAc3B","file":"NodeOps.d.ts","sourcesContent":["import State from '../shared/State';\nimport {\n getNode,\n deleteNode,\n getNodeTypes,\n getNodesByType,\n} from '../api/NodeApi';\nimport { getTrees } from '../api/TreeApi';\nimport {\n printMessage,\n createProgressIndicator,\n updateProgressIndicator,\n stopProgressIndicator,\n} from './utils/Console';\nimport { NodeClassificationType } from './OpsTypes';\nimport { NodeSkeleton } from '../api/ApiTypes';\n\nexport default class NodeOps {\n state: State;\n constructor(state: State) {\n this.state = state;\n }\n\n /**\n * Find all node configuration objects that are no longer referenced by any tree\n * @returns {Promise<unknown[]>} a promise that resolves to an array of orphaned nodes\n */\n async findOrphanedNodes(): Promise<unknown[]> {\n return findOrphanedNodes({ state: this.state });\n }\n\n /**\n * Remove orphaned nodes\n * @param {NodeSkeleton[]} orphanedNodes Pass in an array of orphaned node configuration objects to remove\n * @returns {Promise<NodeSkeleton[]>} a promise that resolves to an array nodes that encountered errors deleting\n */\n async removeOrphanedNodes(\n orphanedNodes: NodeSkeleton[]\n ): Promise<NodeSkeleton[]> {\n return removeOrphanedNodes({ orphanedNodes, state: this.state });\n }\n\n /**\n * Analyze if a node is a premium node.\n * @param {string} nodeType Node type\n * @returns {boolean} True if the node type is premium, false otherwise.\n */\n isPremiumNode(nodeType: string): boolean {\n return isPremiumNode(nodeType);\n }\n\n /**\n * Analyze if a node is a cloud-only node.\n * @param {string} nodeType Node type\n * @returns {boolean} True if the node type is cloud-only, false otherwise.\n */\n isCloudOnlyNode(nodeType: string): boolean {\n return isCloudOnlyNode(nodeType);\n }\n\n /**\n * Analyze if a node is custom.\n * @param {string} nodeType Node type\n * @returns {boolean} True if the node type is custom, false otherwise.\n */\n isCustomNode(nodeType: string): boolean {\n return isCustomNode({ nodeType, state: this.state });\n }\n\n /**\n * Get a node's classifications, which can be one or multiple of:\n * - standard: can run on any instance of a ForgeRock platform\n * - cloud: utilize nodes, which are exclusively available in the ForgeRock Identity Cloud\n * - premium: utilizes nodes, which come at a premium\n * @param {string} nodeType Node type\n * @returns {NodeClassificationType[]} an array of one or multiple classifications\n */\n getNodeClassification(nodeType: string): NodeClassificationType[] {\n return getNodeClassification({ nodeType, state: this.state });\n }\n}\n\nexport enum NodeClassification {\n STANDARD = 'standard',\n CUSTOM = 'custom',\n CLOUD = 'cloud',\n PREMIUM = 'premium',\n}\n\nconst containerNodes = ['PageNode', 'CustomPageNode'];\n\n/**\n * Find all node configuration objects that are no longer referenced by any tree\n * @returns {Promise<unknown[]>} a promise that resolves to an array of orphaned nodes\n */\nexport async function findOrphanedNodes({\n state,\n}: {\n state: State;\n}): Promise<unknown[]> {\n const allNodes = [];\n const orphanedNodes = [];\n let types = [];\n const allJourneys = (await getTrees({ state })).result;\n let errorMessage = '';\n const errorTypes = [];\n\n createProgressIndicator({\n total: undefined,\n message: `Counting total nodes...`,\n type: 'indeterminate',\n state,\n });\n try {\n types = (await getNodeTypes({ state })).result;\n } catch (error) {\n printMessage({\n message: 'Error retrieving all available node types:',\n type: 'error',\n state,\n });\n printMessage({ message: error.response.data, type: 'error', state });\n return [];\n }\n for (const type of types) {\n try {\n // eslint-disable-next-line no-await-in-loop, no-loop-func\n const nodes = (await getNodesByType({ nodeType: type._id, state }))\n .result;\n for (const node of nodes) {\n allNodes.push(node);\n updateProgressIndicator({\n message: `${allNodes.length} total nodes${errorMessage}`,\n state,\n });\n }\n } catch (error) {\n errorTypes.push(type._id);\n errorMessage = ` (Skipped type(s): ${errorTypes})`['yellow'];\n updateProgressIndicator({\n message: `${allNodes.length} total nodes${errorMessage}`,\n state,\n });\n }\n }\n if (errorTypes.length > 0) {\n stopProgressIndicator({\n message: `${allNodes.length} total nodes${errorMessage}`,\n state,\n status: 'warn',\n });\n } else {\n stopProgressIndicator({\n message: `${allNodes.length} total nodes`,\n status: 'success',\n state,\n });\n }\n\n createProgressIndicator({\n total: undefined,\n message: 'Counting active nodes...',\n type: 'indeterminate',\n state,\n });\n const activeNodes = [];\n for (const journey of allJourneys) {\n for (const nodeId in journey.nodes) {\n if ({}.hasOwnProperty.call(journey.nodes, nodeId)) {\n activeNodes.push(nodeId);\n updateProgressIndicator({\n message: `${activeNodes.length} active nodes`,\n state,\n });\n const node = journey.nodes[nodeId];\n if (containerNodes.includes(node.nodeType)) {\n const containerNode = await getNode({\n nodeId,\n nodeType: node.nodeType,\n state,\n });\n for (const innerNode of containerNode.nodes) {\n activeNodes.push(innerNode._id);\n updateProgressIndicator({\n message: `${activeNodes.length} active nodes`,\n state,\n });\n }\n }\n }\n }\n }\n stopProgressIndicator({\n message: `${activeNodes.length} active nodes`,\n status: 'success',\n state,\n });\n\n createProgressIndicator({\n total: undefined,\n message: 'Calculating orphaned nodes...',\n type: 'indeterminate',\n state,\n });\n const diff = allNodes.filter((x) => !activeNodes.includes(x._id));\n for (const orphanedNode of diff) {\n orphanedNodes.push(orphanedNode);\n }\n stopProgressIndicator({\n message: `${orphanedNodes.length} orphaned nodes`,\n status: 'success',\n state,\n });\n return orphanedNodes;\n}\n\n/**\n * Remove orphaned nodes\n * @param {NodeSkeleton[]} orphanedNodes Pass in an array of orphaned node configuration objects to remove\n * @returns {Promise<NodeSkeleton[]>} a promise that resolves to an array nodes that encountered errors deleting\n */\nexport async function removeOrphanedNodes({\n orphanedNodes,\n state,\n}: {\n orphanedNodes: NodeSkeleton[];\n state: State;\n}): Promise<NodeSkeleton[]> {\n const errorNodes = [];\n createProgressIndicator({\n total: orphanedNodes.length,\n message: 'Removing orphaned nodes...',\n state,\n });\n for (const node of orphanedNodes) {\n updateProgressIndicator({ message: `Removing ${node['_id']}...`, state });\n try {\n await deleteNode({\n nodeId: node['_id'],\n nodeType: node['_type']['_id'],\n state,\n });\n } catch (deleteError) {\n errorNodes.push(node);\n printMessage({ message: ` ${deleteError}`, type: 'error', state });\n }\n }\n stopProgressIndicator({\n message: `Removed ${orphanedNodes.length} orphaned nodes.`,\n state,\n });\n return errorNodes;\n}\n\nconst OOTB_NODE_TYPES_7 = [\n 'AcceptTermsAndConditionsNode',\n 'AccountActiveDecisionNode',\n 'AccountLockoutNode',\n 'AgentDataStoreDecisionNode',\n 'AnonymousSessionUpgradeNode',\n 'AnonymousUserNode',\n 'AttributeCollectorNode',\n 'AttributePresentDecisionNode',\n 'AttributeValueDecisionNode',\n 'AuthLevelDecisionNode',\n 'ChoiceCollectorNode',\n 'ConsentNode',\n 'CookiePresenceDecisionNode',\n 'CreateObjectNode',\n 'CreatePasswordNode',\n 'DataStoreDecisionNode',\n 'DeviceGeoFencingNode',\n 'DeviceLocationMatchNode',\n 'DeviceMatchNode',\n 'DeviceProfileCollectorNode',\n 'DeviceSaveNode',\n 'DeviceTamperingVerificationNode',\n 'DisplayUserNameNode',\n 'EmailSuspendNode',\n 'EmailTemplateNode',\n 'IdentifyExistingUserNode',\n 'IncrementLoginCountNode',\n 'InnerTreeEvaluatorNode',\n 'IotAuthenticationNode',\n 'IotRegistrationNode',\n 'KbaCreateNode',\n 'KbaDecisionNode',\n 'KbaVerifyNode',\n 'LdapDecisionNode',\n 'LoginCountDecisionNode',\n 'MessageNode',\n 'MetadataNode',\n 'MeterNode',\n 'ModifyAuthLevelNode',\n 'OneTimePasswordCollectorDecisionNode',\n 'OneTimePasswordGeneratorNode',\n 'OneTimePasswordSmsSenderNode',\n 'OneTimePasswordSmtpSenderNode',\n 'PageNode',\n 'PasswordCollectorNode',\n 'PatchObjectNode',\n 'PersistentCookieDecisionNode',\n 'PollingWaitNode',\n 'ProfileCompletenessDecisionNode',\n 'ProvisionDynamicAccountNode',\n 'ProvisionIdmAccountNode',\n 'PushAuthenticationSenderNode',\n 'PushResultVerifierNode',\n 'QueryFilterDecisionNode',\n 'RecoveryCodeCollectorDecisionNode',\n 'RecoveryCodeDisplayNode',\n 'RegisterLogoutWebhookNode',\n 'RemoveSessionPropertiesNode',\n 'RequiredAttributesDecisionNode',\n 'RetryLimitDecisionNode',\n 'ScriptedDecisionNode',\n 'SelectIdPNode',\n 'SessionDataNode',\n 'SetFailureUrlNode',\n 'SetPersistentCookieNode',\n 'SetSessionPropertiesNode',\n 'SetSuccessUrlNode',\n 'SocialFacebookNode',\n 'SocialGoogleNode',\n 'SocialNode',\n 'SocialOAuthIgnoreProfileNode',\n 'SocialOpenIdConnectNode',\n 'SocialProviderHandlerNode',\n 'TermsAndConditionsDecisionNode',\n 'TimeSinceDecisionNode',\n 'TimerStartNode',\n 'TimerStopNode',\n 'UsernameCollectorNode',\n 'ValidatedPasswordNode',\n 'ValidatedUsernameNode',\n 'WebAuthnAuthenticationNode',\n 'WebAuthnDeviceStorageNode',\n 'WebAuthnRegistrationNode',\n 'ZeroPageLoginNode',\n 'product-CertificateCollectorNode',\n 'product-CertificateUserExtractorNode',\n 'product-CertificateValidationNode',\n 'product-KerberosNode',\n 'product-ReCaptchaNode',\n 'product-Saml2Node',\n 'product-WriteFederationInformationNode',\n];\n\nconst OOTB_NODE_TYPES_7_1 = [\n 'PushRegistrationNode',\n 'GetAuthenticatorAppNode',\n 'MultiFactorRegistrationOptionsNode',\n 'OptOutMultiFactorAuthenticationNode',\n].concat(OOTB_NODE_TYPES_7);\n\nconst OOTB_NODE_TYPES_7_2 = [\n 'OathRegistrationNode',\n 'OathTokenVerifierNode',\n 'PassthroughAuthenticationNode',\n 'ConfigProviderNode',\n 'DebugNode',\n].concat(OOTB_NODE_TYPES_7_1);\n\nconst OOTB_NODE_TYPES_7_3 = [].concat(OOTB_NODE_TYPES_7_2);\n\nconst OOTB_NODE_TYPES_6_5 = [\n 'AbstractSocialAuthLoginNode',\n 'AccountLockoutNode',\n 'AgentDataStoreDecisionNode',\n 'AnonymousUserNode',\n 'AuthLevelDecisionNode',\n 'ChoiceCollectorNode',\n 'CookiePresenceDecisionNode',\n 'CreatePasswordNode',\n 'DataStoreDecisionNode',\n 'InnerTreeEvaluatorNode',\n 'LdapDecisionNode',\n 'MessageNode',\n 'MetadataNode',\n 'MeterNode',\n 'ModifyAuthLevelNode',\n 'OneTimePasswordCollectorDecisionNode',\n 'OneTimePasswordGeneratorNode',\n 'OneTimePasswordSmsSenderNode',\n 'OneTimePasswordSmtpSenderNode',\n 'PageNode',\n 'PasswordCollectorNode',\n 'PersistentCookieDecisionNode',\n 'PollingWaitNode',\n 'ProvisionDynamicAccountNode',\n 'ProvisionIdmAccountNode',\n 'PushAuthenticationSenderNode',\n 'PushResultVerifierNode',\n 'RecoveryCodeCollectorDecisionNode',\n 'RecoveryCodeDisplayNode',\n 'RegisterLogoutWebhookNode',\n 'RemoveSessionPropertiesNode',\n 'RetryLimitDecisionNode',\n 'ScriptedDecisionNode',\n 'SessionDataNode',\n 'SetFailureUrlNode',\n 'SetPersistentCookieNode',\n 'SetSessionPropertiesNode',\n 'SetSuccessUrlNode',\n 'SocialFacebookNode',\n 'SocialGoogleNode',\n 'SocialNode',\n 'SocialOAuthIgnoreProfileNode',\n 'SocialOpenIdConnectNode',\n 'TimerStartNode',\n 'TimerStopNode',\n 'UsernameCollectorNode',\n 'WebAuthnAuthenticationNode',\n 'WebAuthnRegistrationNode',\n 'ZeroPageLoginNode',\n];\n\nconst OOTB_NODE_TYPES_6 = [\n 'AbstractSocialAuthLoginNode',\n 'AccountLockoutNode',\n 'AgentDataStoreDecisionNode',\n 'AnonymousUserNode',\n 'AuthLevelDecisionNode',\n 'ChoiceCollectorNode',\n 'CookiePresenceDecisionNode',\n 'CreatePasswordNode',\n 'DataStoreDecisionNode',\n 'InnerTreeEvaluatorNode',\n 'LdapDecisionNode',\n 'MessageNode',\n 'MetadataNode',\n 'MeterNode',\n 'ModifyAuthLevelNode',\n 'OneTimePasswordCollectorDecisionNode',\n 'OneTimePasswordGeneratorNode',\n 'OneTimePasswordSmsSenderNode',\n 'OneTimePasswordSmtpSenderNode',\n 'PageNode',\n 'PasswordCollectorNode',\n 'PersistentCookieDecisionNode',\n 'PollingWaitNode',\n 'ProvisionDynamicAccountNode',\n 'ProvisionIdmAccountNode',\n 'PushAuthenticationSenderNode',\n 'PushResultVerifierNode',\n 'RecoveryCodeCollectorDecisionNode',\n 'RecoveryCodeDisplayNode',\n 'RegisterLogoutWebhookNode',\n 'RemoveSessionPropertiesNode',\n 'RetryLimitDecisionNode',\n 'ScriptedDecisionNode',\n 'SessionDataNode',\n 'SetFailureUrlNode',\n 'SetPersistentCookieNode',\n 'SetSessionPropertiesNode',\n 'SetSuccessUrlNode',\n 'SocialFacebookNode',\n 'SocialGoogleNode',\n 'SocialNode',\n 'SocialOAuthIgnoreProfileNode',\n 'SocialOpenIdConnectNode',\n 'TimerStartNode',\n 'TimerStopNode',\n 'UsernameCollectorNode',\n 'WebAuthnAuthenticationNode',\n 'WebAuthnRegistrationNode',\n 'ZeroPageLoginNode',\n];\n\nconst CLOUD_ONLY_NODE_TYPES = [\n 'IdentityStoreDecisionNode',\n 'AutonomousAccessSignalNode',\n 'AutonomousAccessDecisionNode',\n 'AutonomousAccessResultNode',\n];\n\nconst PREMIUM_NODE_TYPES = [\n 'AutonomousAccessSignalNode',\n 'AutonomousAccessDecisionNode',\n 'AutonomousAccessResultNode',\n];\n\n/**\n * Analyze if a node is a premium node.\n * @param {string} nodeType Node type\n * @returns {boolean} True if the node type is premium, false otherwise.\n */\nexport function isPremiumNode(nodeType: string): boolean {\n return PREMIUM_NODE_TYPES.includes(nodeType);\n}\n\n/**\n * Analyze if a node is a cloud-only node.\n * @param {string} nodeType Node type\n * @returns {boolean} True if the node type is cloud-only, false otherwise.\n */\nexport function isCloudOnlyNode(nodeType: string): boolean {\n return CLOUD_ONLY_NODE_TYPES.includes(nodeType);\n}\n\n/**\n * Analyze if a node is custom.\n * @param {string} nodeType Node type\n * @returns {boolean} True if the node type is custom, false otherwise.\n */\nexport function isCustomNode({\n nodeType,\n state,\n}: {\n nodeType: string;\n state: State;\n}): boolean {\n let ootbNodeTypes = [];\n switch (state.getAmVersion()) {\n case '7.1.0':\n ootbNodeTypes = OOTB_NODE_TYPES_7_1.slice(0);\n break;\n case '7.2.0':\n ootbNodeTypes = OOTB_NODE_TYPES_7_2.slice(0);\n break;\n case '7.3.0':\n ootbNodeTypes = OOTB_NODE_TYPES_7_3.slice(0);\n break;\n case '7.0.0':\n case '7.0.1':\n case '7.0.2':\n ootbNodeTypes = OOTB_NODE_TYPES_7.slice(0);\n break;\n case '6.5.3':\n case '6.5.2.3':\n case '6.5.2.2':\n case '6.5.2.1':\n case '6.5.2':\n case '6.5.1':\n case '6.5.0.2':\n case '6.5.0.1':\n ootbNodeTypes = OOTB_NODE_TYPES_6_5.slice(0);\n break;\n case '6.0.0.7':\n case '6.0.0.6':\n case '6.0.0.5':\n case '6.0.0.4':\n case '6.0.0.3':\n case '6.0.0.2':\n case '6.0.0.1':\n case '6.0.0':\n ootbNodeTypes = OOTB_NODE_TYPES_6.slice(0);\n break;\n default:\n return true;\n }\n return (\n !ootbNodeTypes.includes(nodeType) &&\n !isPremiumNode(nodeType) &&\n !isCloudOnlyNode(nodeType)\n );\n}\n\n/**\n * Get a node's classifications, which can be one or multiple of:\n * - standard: can run on any instance of a ForgeRock platform\n * - cloud: utilize nodes, which are exclusively available in the ForgeRock Identity Cloud\n * - premium: utilizes nodes, which come at a premium\n * @param {string} nodeType Node type\n * @returns {NodeClassification[]} an array of one or multiple classifications\n */\nexport function getNodeClassification({\n nodeType,\n state,\n}: {\n nodeType: string;\n state: State;\n}): NodeClassificationType[] {\n const classifications: NodeClassificationType[] = [];\n const premium = isPremiumNode(nodeType);\n const custom = isCustomNode({ nodeType, state });\n const cloud = isCloudOnlyNode(nodeType);\n if (custom) {\n classifications.push(NodeClassification.CUSTOM);\n } else if (cloud) {\n classifications.push(NodeClassification.CLOUD);\n } else {\n classifications.push(NodeClassification.STANDARD);\n }\n if (premium) classifications.push(NodeClassification.PREMIUM);\n return classifications;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ops/OAuth2ClientOps.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,EACL,2BAA2B,EAC3B,oBAAoB,EACpB,cAAc,EACf,MAAM,iBAAiB,CAAC;AAKzB,OAAO,KAAK,MAAM,iBAAiB,CAAC;AAGpC,MAAM,CAAC,OAAO,OAAO,eAAe;IAClC,KAAK,EAAE,KAAK,CAAC;gBACD,KAAK,EAAE,KAAK;IAIxB;;;OAGG;IACG,gBAAgB;IAItB;;;;OAIG;IACG,eAAe,CAAC,QAAQ,EAAE,MAAM;IAItC;;;;;OAKG;IACG,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,UAAU,EAAE,oBAAoB;IAIxE;;;;OAIG;IACG,kBAAkB,CAAC,QAAQ,EAAE,MAAM;IAIzC;;;;OAIG;IACG,mBAAmB,CACvB,OAAO,GAAE,yBAAiE,GACzE,OAAO,CAAC,2BAA2B,CAAC;IAIvC;;;;;OAKG;IACG,kBAAkB,CACtB,QAAQ,EAAE,MAAM,EAChB,OAAO,GAAE,yBAAiE,GACzE,OAAO,CAAC,2BAA2B,CAAC;IAIvC;;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ClientOps.d.ts","sourcesContent":["import {\n getOAuth2Client as _getOAuth2Client,\n getOAuth2Clients as _getOAuth2Clients,\n putOAuth2Client as _putOAuth2Client,\n deleteOAuth2Client as _deleteOAuth2Client,\n} from '../api/OAuth2ClientApi';\nimport { ExportMetaData } from './OpsTypes';\nimport {\n NoIdObjectSkeletonInterface,\n OAuth2ClientSkeleton,\n ScriptSkeleton,\n} from '../api/ApiTypes';\nimport { getMetadata } from './utils/ExportImportUtils';\nimport { debugMessage, printMessage } from './utils/Console';\nimport { convertBase64TextToArray } from './utils/ExportImportUtils';\nimport { getOAuth2Provider } from './OAuth2ProviderOps';\nimport State from '../shared/State';\nimport { getScript, putScript } from './ScriptOps';\n\nexport default class OAuth2ClientOps {\n state: State;\n constructor(state: State) {\n this.state = state;\n }\n\n /**\n * Get all OAuth2 clients\n * @returns {Promise<any[]>} a promise that resolves to an array of oauth2client objects\n */\n async getOAuth2Clients() {\n return getOAuth2Clients({ state: this.state });\n }\n\n /**\n * Get OAuth2 client\n * @param {string} clientId client id\n * @returns {Promise<any>} a promise that resolves to an oauth2client object\n */\n async getOAuth2Client(clientId: string) {\n return getOAuth2Client({ clientId, state: this.state });\n }\n\n /**\n * Put OAuth2 client\n * @param {string} clientId client id\n * @param {any} clientData oauth2client object\n * @returns {Promise<any>} a promise that resolves to an oauth2client object\n */\n async putOAuth2Client(clientId: string, clientData: OAuth2ClientSkeleton) {\n return putOAuth2Client({ clientId, clientData, state: this.state });\n }\n\n /**\n * Delete OAuth2 client\n * @param {string} clientId client id\n * @returns {Promise<any>} a promise that resolves to an oauth2client object\n */\n async deleteOAuth2Client(clientId: string) {\n return deleteOAuth2Client({ clientId, state: this.state });\n }\n\n /**\n * Export all OAuth2 clients\n * @param {OAuth2ClientExportOptions} options export options\n * @returns {OAuth2ClientExportInterface} export data\n */\n async exportOAuth2Clients(\n options: OAuth2ClientExportOptions = { useStringArrays: true, deps: true }\n ): Promise<OAuth2ClientExportInterface> {\n return exportOAuth2Clients({ options, state: this.state });\n }\n\n /**\n * Export OAuth2 client by ID\n * @param {string} clientId oauth2 client id\n * @param {OAuth2ClientExportOptions} options export options\n * @returns {OAuth2ClientExportInterface} export data\n */\n async exportOAuth2Client(\n clientId: string,\n options: OAuth2ClientExportOptions = { useStringArrays: true, deps: true }\n ): Promise<OAuth2ClientExportInterface> {\n return exportOAuth2Client({ clientId, options, state: this.state });\n }\n\n /**\n * Import OAuth2 Client by ID\n * @param {string} clientId client id\n * @param {OAuth2ClientExportInterface} importData import data\n * @param {OAuth2ClientImportOptions} options import options\n */\n async importOAuth2Client(\n clientId: string,\n importData: OAuth2ClientExportInterface,\n options: OAuth2ClientImportOptions = { deps: true }\n ) {\n return importOAuth2Client({\n clientId,\n importData,\n options,\n state: this.state,\n });\n }\n\n /**\n * Import first OAuth2 Client\n * @param {OAuth2ClientExportInterface} importData import data\n * @param {OAuth2ClientImportOptions} options import options\n */\n async importFirstOAuth2Client(\n importData: OAuth2ClientExportInterface,\n options: OAuth2ClientImportOptions = { deps: true }\n ) {\n return importFirstOAuth2Client({ importData, options, state: this.state });\n }\n\n /**\n * Import OAuth2 Clients\n * @param {OAuth2ClientExportInterface} importData import data\n * @param {OAuth2ClientImportOptions} options import options\n * @returns {Promise<unknown[]>} array of imported oauth2 clients\n */\n async importOAuth2Clients(\n importData: OAuth2ClientExportInterface,\n options: OAuth2ClientImportOptions = { deps: true }\n ): Promise<unknown[]> {\n return importOAuth2Clients({ importData, options, state: this.state });\n }\n}\n\n/**\n * OAuth2 client export options\n */\nexport interface OAuth2ClientExportOptions {\n /**\n * Use string arrays to store multi-line text in scripts.\n */\n useStringArrays: boolean;\n /**\n * Include any dependencies (scripts).\n */\n deps: boolean;\n}\n\n/**\n * OAuth2 client import options\n */\nexport interface OAuth2ClientImportOptions {\n /**\n * Include any dependencies (scripts).\n */\n deps: boolean;\n}\n\nexport interface OAuth2ClientExportInterface {\n meta?: ExportMetaData;\n script: Record<string, ScriptSkeleton>;\n application: Record<string, OAuth2ClientSkeleton>;\n}\n\n/**\n * Create an empty OAuth2 client export template\n * @returns {OAuth2ClientExportInterface} an empty OAuth2 client export template\n */\nfunction createOAuth2ClientExportTemplate({\n state,\n}: {\n state: State;\n}): OAuth2ClientExportInterface {\n return {\n meta: getMetadata({ state }),\n script: {},\n application: {},\n } as OAuth2ClientExportInterface;\n}\n\n/**\n * Get all OAuth2 clients\n * @returns {Promise<any[]>} a promise that resolves to an array of oauth2client objects\n */\nexport async function getOAuth2Clients({ state }: { state: State }) {\n const clients = (await _getOAuth2Clients({ state })).result;\n return clients;\n}\n\n/**\n * Get OAuth2 client\n * @param {string} clientId client id\n * @returns {Promise<any>} a promise that resolves to an oauth2client object\n */\nexport async function getOAuth2Client({\n clientId,\n state,\n}: {\n clientId: string;\n state: State;\n}) {\n return _getOAuth2Client({ id: clientId, state });\n}\n\n/**\n * Put OAuth2 client\n * @param {string} clientId client id\n * @param {any} clientData oauth2client object\n * @returns {Promise<any>} a promise that resolves to an oauth2client object\n */\nexport async function putOAuth2Client({\n clientId,\n clientData,\n state,\n}: {\n clientId: string;\n clientData: OAuth2ClientSkeleton | NoIdObjectSkeletonInterface;\n state: State;\n}) {\n debugMessage(`OAuth2ClientOps.putOAuth2Client: start`);\n try {\n const response = await _putOAuth2Client({\n id: clientId,\n clientData,\n state,\n });\n debugMessage(`OAuth2ClientOps.putOAuth2Client: end`);\n return response;\n } catch (error) {\n if (\n error.response?.status === 400 &&\n error.response?.data?.message === 'Invalid attribute specified.'\n ) {\n const { validAttributes } = error.response.data.detail;\n validAttributes.push('_id');\n for (const key of Object.keys(clientData)) {\n if (typeof clientData[key] === 'object') {\n for (const attribute of Object.keys(clientData[key])) {\n if (!validAttributes.includes(attribute)) {\n if (state.getVerbose())\n printMessage(\n `\\n- Removing invalid attribute: ${key}.${attribute}`,\n 'warn'\n );\n delete clientData[key][attribute];\n }\n }\n }\n }\n const response = await _putOAuth2Client({\n id: clientId,\n clientData,\n state,\n });\n debugMessage(`OAuth2ClientOps.putOAuth2Client: end`);\n return response;\n } else {\n throw error;\n }\n }\n}\n\n/**\n * Delete OAuth2 client\n * @param {string} clientId client id\n * @returns {Promise<any>} a promise that resolves to an oauth2client object\n */\nexport async function deleteOAuth2Client({\n clientId,\n state,\n}: {\n clientId: string;\n state: State;\n}) {\n return _deleteOAuth2Client({ id: clientId, state });\n}\n\n/**\n * Helper function to export dependencies of an OAuth2 Client\n * @param {unknown} clientData oauth2 client data\n * @param {OAuth2ClientExportOptions} options export options\n * @param {OAuth2ClientExportInterface} exportData export data\n */\nasync function exportOAuth2ClientDependencies(\n clientData: unknown,\n options: OAuth2ClientExportOptions,\n exportData: OAuth2ClientExportInterface,\n state: State\n) {\n debugMessage(\n `OAuth2ClientOps.exportOAuth2ClientDependencies: start [client=${clientData['_id']}]`\n );\n if (clientData['overrideOAuth2ClientConfig']) {\n for (const key of Object.keys(clientData['overrideOAuth2ClientConfig'])) {\n if (key.endsWith('Script')) {\n const scriptId = clientData['overrideOAuth2ClientConfig'][key];\n if (scriptId !== '[Empty]' && !exportData.script[scriptId]) {\n try {\n debugMessage(`- ${scriptId} referenced by ${clientData['_id']}`);\n const scriptData = await getScript({ scriptId, state });\n if (options.useStringArrays)\n scriptData.script = convertBase64TextToArray(\n scriptData.script as string\n );\n exportData.script[scriptId] = scriptData;\n } catch (error) {\n if (\n !(\n error.response?.status === 403 &&\n error.response?.data?.message ===\n 'This operation is not available in ForgeRock Identity Cloud.'\n )\n ) {\n error.message = `Error retrieving script ${scriptId} referenced by ${key} key in client ${clientData['_id']}: ${error.message}`;\n throw error;\n }\n }\n }\n }\n }\n }\n debugMessage(`OAuth2ClientOps.exportOAuth2ClientDependencies: end`);\n}\n\n/**\n * Export all OAuth2 clients\n * @param {OAuth2ClientExportOptions} options export options\n * @returns {OAuth2ClientExportInterface} export data\n */\nexport async function exportOAuth2Clients({\n options = { useStringArrays: true, deps: true },\n state,\n}: {\n options?: OAuth2ClientExportOptions;\n state: State;\n}): Promise<OAuth2ClientExportInterface> {\n debugMessage(`OAuth2ClientOps.exportOAuth2Clients: start`);\n const exportData = createOAuth2ClientExportTemplate({ state });\n const errors = [];\n try {\n const provider = await getOAuth2Provider({ state });\n const clients = await getOAuth2Clients({ state });\n for (const client of clients) {\n try {\n client._provider = provider;\n exportData.application[client._id] = client;\n if (options.deps) {\n await exportOAuth2ClientDependencies(\n client,\n options,\n exportData,\n state\n );\n }\n } catch (error) {\n errors.push(error);\n }\n }\n } catch (error) {\n errors.push(error);\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Export error:\\n${errorMessages}`);\n }\n debugMessage(`OAuth2ClientOps.exportOAuth2Clients: end`);\n return exportData;\n}\n\n/**\n * Export OAuth2 client by ID\n * @param {string} clientId oauth2 client id\n * @param {OAuth2ClientExportOptions} options export options\n * @returns {OAuth2ClientExportInterface} export data\n */\nexport async function exportOAuth2Client({\n clientId,\n options = { useStringArrays: true, deps: true },\n state,\n}: {\n clientId: string;\n options?: OAuth2ClientExportOptions;\n state: State;\n}): Promise<OAuth2ClientExportInterface> {\n debugMessage(`OAuth2ClientOps.exportOAuth2Client: start`);\n const exportData = createOAuth2ClientExportTemplate({ state });\n const errors = [];\n try {\n const clientData = await getOAuth2Client({ clientId, state });\n clientData._provider = await getOAuth2Provider({ state });\n exportData.application[clientData._id] = clientData;\n if (options.deps) {\n await exportOAuth2ClientDependencies(\n clientData,\n options,\n exportData,\n state\n );\n }\n } catch (error) {\n errors.push(error);\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Export error:\\n${errorMessages}`);\n }\n debugMessage(`OAuth2ClientOps.exportOAuth2Client: end`);\n return exportData;\n}\n\n/**\n * Helper function to export dependencies of an OAuth2 Client\n * @param {unknown} clientData oauth2 client data\n * @param {OAuth2ClientExportInterface} importData import data\n */\nasync function importOAuth2ClientDependencies(\n clientData: unknown,\n importData: OAuth2ClientExportInterface,\n state: State\n) {\n for (const key of Object.keys(clientData['overrideOAuth2ClientConfig'])) {\n if (key.endsWith('Script')) {\n const scriptId = clientData['overrideOAuth2ClientConfig'][key];\n if (scriptId !== '[Empty]' && importData.script[scriptId]) {\n const scriptData: ScriptSkeleton = importData.script[scriptId];\n await putScript({ scriptId, scriptData, state });\n }\n }\n }\n}\n\n/**\n * Import OAuth2 Client by ID\n * @param {string} clientId client id\n * @param {OAuth2ClientExportInterface} importData import data\n * @param {OAuth2ClientImportOptions} options import options\n */\nexport async function importOAuth2Client({\n clientId,\n importData,\n options = { deps: true },\n state,\n}: {\n clientId: string;\n importData: OAuth2ClientExportInterface;\n options?: OAuth2ClientImportOptions;\n state: State;\n}) {\n let response = null;\n const errors = [];\n const imported = [];\n for (const id of Object.keys(importData.application)) {\n if (id === clientId) {\n try {\n const clientData = importData.application[id];\n delete clientData._provider;\n delete clientData._rev;\n if (options.deps) {\n await importOAuth2ClientDependencies(clientData, importData, state);\n }\n response = await putOAuth2Client({ clientId: id, clientData, state });\n imported.push(id);\n } catch (error) {\n errors.push(error);\n }\n }\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Import error:\\n${errorMessages}`);\n }\n if (0 === imported.length) {\n throw new Error(`Import error:\\n${clientId} not found in import data!`);\n }\n return response;\n}\n\n/**\n * Import first OAuth2 Client\n * @param {OAuth2ClientExportInterface} importData import data\n * @param {OAuth2ClientImportOptions} options import options\n */\nexport async function importFirstOAuth2Client({\n importData,\n options = { deps: true },\n state,\n}: {\n importData: OAuth2ClientExportInterface;\n options?: OAuth2ClientImportOptions;\n state: State;\n}) {\n let response = null;\n const errors = [];\n const imported = [];\n for (const id of Object.keys(importData.application)) {\n try {\n const clientData = importData.application[id];\n delete clientData._provider;\n delete clientData._rev;\n if (options.deps) {\n await importOAuth2ClientDependencies(clientData, importData, state);\n }\n response = await putOAuth2Client({ clientId: id, clientData, state });\n imported.push(id);\n } catch (error) {\n errors.push(error);\n }\n break;\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Import error:\\n${errorMessages}`);\n }\n if (0 === imported.length) {\n throw new Error(`Import error:\\nNo clients found in import data!`);\n }\n return response;\n}\n\n/**\n * Import OAuth2 Clients\n * @param {OAuth2ClientExportInterface} importData import data\n * @param {OAuth2ClientImportOptions} options import options\n * @returns {Promise<unknown[]>} array of imported oauth2 clients\n */\nexport async function importOAuth2Clients({\n importData,\n options = { deps: true },\n state,\n}: {\n importData: OAuth2ClientExportInterface;\n options?: OAuth2ClientImportOptions;\n state: State;\n}): Promise<unknown[]> {\n const response = [];\n const errors = [];\n const imported = [];\n for (const id of Object.keys(importData.application)) {\n try {\n const clientData = importData.application[id];\n delete clientData._provider;\n delete clientData._rev;\n if (options.deps) {\n await importOAuth2ClientDependencies(clientData, importData, state);\n }\n response.push(await putOAuth2Client({ clientId: id, clientData, state }));\n imported.push(id);\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Import error:\\n${errorMessages}`);\n }\n if (0 === imported.length) {\n throw new Error(`Import error:\\nNo clients found in import data!`);\n }\n return response;\n}\n"]}
1
+ {"version":3,"sources":["../src/ops/OAuth2ClientOps.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,EACL,2BAA2B,EAC3B,oBAAoB,EACpB,cAAc,EACf,MAAM,iBAAiB,CAAC;AAKzB,OAAO,KAAK,MAAM,iBAAiB,CAAC;AAGpC,MAAM,CAAC,OAAO,OAAO,eAAe;IAClC,KAAK,EAAE,KAAK,CAAC;gBACD,KAAK,EAAE,KAAK;IAIxB;;;OAGG;IACG,gBAAgB;IAItB;;;;OAIG;IACG,eAAe,CAAC,QAAQ,EAAE,MAAM;IAItC;;;;;OAKG;IACG,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,UAAU,EAAE,oBAAoB;IAIxE;;;;OAIG;IACG,kBAAkB,CAA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;AACH,wBAAsB,mBAAmB,CAAC,EACxC,UAAU,EACV,OAAwB,EACxB,KAAK,GACN,EAAE;IACD,UAAU,EAAE,2BAA2B,CAAC;IACxC,OAAO,CAAC,EAAE,yBAAyB,CAAC;IACpC,KAAK,EAAE,KAAK,CAAC;CACd,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC,CA0BrB","file":"OAuth2ClientOps.d.ts","sourcesContent":["import {\n getOAuth2Client as _getOAuth2Client,\n getOAuth2Clients as _getOAuth2Clients,\n putOAuth2Client as _putOAuth2Client,\n deleteOAuth2Client as _deleteOAuth2Client,\n} from '../api/OAuth2ClientApi';\nimport { ExportMetaData } from './OpsTypes';\nimport {\n NoIdObjectSkeletonInterface,\n OAuth2ClientSkeleton,\n ScriptSkeleton,\n} from '../api/ApiTypes';\nimport { getMetadata } from './utils/ExportImportUtils';\nimport { debugMessage, printMessage } from './utils/Console';\nimport { convertBase64TextToArray } from './utils/ExportImportUtils';\nimport { getOAuth2Provider } from './OAuth2ProviderOps';\nimport State from '../shared/State';\nimport { getScript, putScript } from './ScriptOps';\n\nexport default class OAuth2ClientOps {\n state: State;\n constructor(state: State) {\n this.state = state;\n }\n\n /**\n * Get all OAuth2 clients\n * @returns {Promise<any[]>} a promise that resolves to an array of oauth2client objects\n */\n async getOAuth2Clients() {\n return getOAuth2Clients({ state: this.state });\n }\n\n /**\n * Get OAuth2 client\n * @param {string} clientId client id\n * @returns {Promise<any>} a promise that resolves to an oauth2client object\n */\n async getOAuth2Client(clientId: string) {\n return getOAuth2Client({ clientId, state: this.state });\n }\n\n /**\n * Put OAuth2 client\n * @param {string} clientId client id\n * @param {any} clientData oauth2client object\n * @returns {Promise<any>} a promise that resolves to an oauth2client object\n */\n async putOAuth2Client(clientId: string, clientData: OAuth2ClientSkeleton) {\n return putOAuth2Client({ clientId, clientData, state: this.state });\n }\n\n /**\n * Delete OAuth2 client\n * @param {string} clientId client id\n * @returns {Promise<any>} a promise that resolves to an oauth2client object\n */\n async deleteOAuth2Client(clientId: string) {\n return deleteOAuth2Client({ clientId, state: this.state });\n }\n\n /**\n * Export all OAuth2 clients\n * @param {OAuth2ClientExportOptions} options export options\n * @returns {OAuth2ClientExportInterface} export data\n */\n async exportOAuth2Clients(\n options: OAuth2ClientExportOptions = { useStringArrays: true, deps: true }\n ): Promise<OAuth2ClientExportInterface> {\n return exportOAuth2Clients({ options, state: this.state });\n }\n\n /**\n * Export OAuth2 client by ID\n * @param {string} clientId oauth2 client id\n * @param {OAuth2ClientExportOptions} options export options\n * @returns {OAuth2ClientExportInterface} export data\n */\n async exportOAuth2Client(\n clientId: string,\n options: OAuth2ClientExportOptions = { useStringArrays: true, deps: true }\n ): Promise<OAuth2ClientExportInterface> {\n return exportOAuth2Client({ clientId, options, state: this.state });\n }\n\n /**\n * Import OAuth2 Client by ID\n * @param {string} clientId client id\n * @param {OAuth2ClientExportInterface} importData import data\n * @param {OAuth2ClientImportOptions} options import options\n */\n async importOAuth2Client(\n clientId: string,\n importData: OAuth2ClientExportInterface,\n options: OAuth2ClientImportOptions = { deps: true }\n ) {\n return importOAuth2Client({\n clientId,\n importData,\n options,\n state: this.state,\n });\n }\n\n /**\n * Import first OAuth2 Client\n * @param {OAuth2ClientExportInterface} importData import data\n * @param {OAuth2ClientImportOptions} options import options\n */\n async importFirstOAuth2Client(\n importData: OAuth2ClientExportInterface,\n options: OAuth2ClientImportOptions = { deps: true }\n ) {\n return importFirstOAuth2Client({ importData, options, state: this.state });\n }\n\n /**\n * Import OAuth2 Clients\n * @param {OAuth2ClientExportInterface} importData import data\n * @param {OAuth2ClientImportOptions} options import options\n * @returns {Promise<unknown[]>} array of imported oauth2 clients\n */\n async importOAuth2Clients(\n importData: OAuth2ClientExportInterface,\n options: OAuth2ClientImportOptions = { deps: true }\n ): Promise<unknown[]> {\n return importOAuth2Clients({ importData, options, state: this.state });\n }\n}\n\n/**\n * OAuth2 client export options\n */\nexport interface OAuth2ClientExportOptions {\n /**\n * Use string arrays to store multi-line text in scripts.\n */\n useStringArrays: boolean;\n /**\n * Include any dependencies (scripts).\n */\n deps: boolean;\n}\n\n/**\n * OAuth2 client import options\n */\nexport interface OAuth2ClientImportOptions {\n /**\n * Include any dependencies (scripts).\n */\n deps: boolean;\n}\n\nexport interface OAuth2ClientExportInterface {\n meta?: ExportMetaData;\n script: Record<string, ScriptSkeleton>;\n application: Record<string, OAuth2ClientSkeleton>;\n}\n\n/**\n * Create an empty OAuth2 client export template\n * @returns {OAuth2ClientExportInterface} an empty OAuth2 client export template\n */\nfunction createOAuth2ClientExportTemplate({\n state,\n}: {\n state: State;\n}): OAuth2ClientExportInterface {\n return {\n meta: getMetadata({ state }),\n script: {},\n application: {},\n } as OAuth2ClientExportInterface;\n}\n\n/**\n * Get all OAuth2 clients\n * @returns {Promise<any[]>} a promise that resolves to an array of oauth2client objects\n */\nexport async function getOAuth2Clients({ state }: { state: State }) {\n const clients = (await _getOAuth2Clients({ state })).result;\n return clients;\n}\n\n/**\n * Get OAuth2 client\n * @param {string} clientId client id\n * @returns {Promise<any>} a promise that resolves to an oauth2client object\n */\nexport async function getOAuth2Client({\n clientId,\n state,\n}: {\n clientId: string;\n state: State;\n}) {\n return _getOAuth2Client({ id: clientId, state });\n}\n\n/**\n * Put OAuth2 client\n * @param {string} clientId client id\n * @param {any} clientData oauth2client object\n * @returns {Promise<any>} a promise that resolves to an oauth2client object\n */\nexport async function putOAuth2Client({\n clientId,\n clientData,\n state,\n}: {\n clientId: string;\n clientData: OAuth2ClientSkeleton | NoIdObjectSkeletonInterface;\n state: State;\n}) {\n debugMessage({ message: `OAuth2ClientOps.putOAuth2Client: start`, state });\n try {\n const response = await _putOAuth2Client({\n id: clientId,\n clientData,\n state,\n });\n debugMessage({ message: `OAuth2ClientOps.putOAuth2Client: end`, state });\n return response;\n } catch (error) {\n if (\n error.response?.status === 400 &&\n error.response?.data?.message === 'Invalid attribute specified.'\n ) {\n const { validAttributes } = error.response.data.detail;\n validAttributes.push('_id');\n for (const key of Object.keys(clientData)) {\n if (typeof clientData[key] === 'object') {\n for (const attribute of Object.keys(clientData[key])) {\n if (!validAttributes.includes(attribute)) {\n if (state.getVerbose())\n printMessage({\n message: `\\n- Removing invalid attribute: ${key}.${attribute}`,\n type: 'warn',\n state,\n });\n delete clientData[key][attribute];\n }\n }\n }\n }\n const response = await _putOAuth2Client({\n id: clientId,\n clientData,\n state,\n });\n debugMessage({ message: `OAuth2ClientOps.putOAuth2Client: end`, state });\n return response;\n } else {\n throw error;\n }\n }\n}\n\n/**\n * Delete OAuth2 client\n * @param {string} clientId client id\n * @returns {Promise<any>} a promise that resolves to an oauth2client object\n */\nexport async function deleteOAuth2Client({\n clientId,\n state,\n}: {\n clientId: string;\n state: State;\n}) {\n return _deleteOAuth2Client({ id: clientId, state });\n}\n\n/**\n * Helper function to export dependencies of an OAuth2 Client\n * @param {unknown} clientData oauth2 client data\n * @param {OAuth2ClientExportOptions} options export options\n * @param {OAuth2ClientExportInterface} exportData export data\n */\nasync function exportOAuth2ClientDependencies(\n clientData: unknown,\n options: OAuth2ClientExportOptions,\n exportData: OAuth2ClientExportInterface,\n state: State\n) {\n debugMessage({\n message: `OAuth2ClientOps.exportOAuth2ClientDependencies: start [client=${clientData['_id']}]`,\n state,\n });\n if (clientData['overrideOAuth2ClientConfig']) {\n for (const key of Object.keys(clientData['overrideOAuth2ClientConfig'])) {\n if (key.endsWith('Script')) {\n const scriptId = clientData['overrideOAuth2ClientConfig'][key];\n if (scriptId !== '[Empty]' && !exportData.script[scriptId]) {\n try {\n debugMessage({\n message: `- ${scriptId} referenced by ${clientData['_id']}`,\n state,\n });\n const scriptData = await getScript({ scriptId, state });\n if (options.useStringArrays)\n scriptData.script = convertBase64TextToArray(\n scriptData.script as string\n );\n exportData.script[scriptId] = scriptData;\n } catch (error) {\n if (\n !(\n error.response?.status === 403 &&\n error.response?.data?.message ===\n 'This operation is not available in ForgeRock Identity Cloud.'\n )\n ) {\n error.message = `Error retrieving script ${scriptId} referenced by ${key} key in client ${clientData['_id']}: ${error.message}`;\n throw error;\n }\n }\n }\n }\n }\n }\n debugMessage({\n message: `OAuth2ClientOps.exportOAuth2ClientDependencies: end`,\n state,\n });\n}\n\n/**\n * Export all OAuth2 clients\n * @param {OAuth2ClientExportOptions} options export options\n * @returns {OAuth2ClientExportInterface} export data\n */\nexport async function exportOAuth2Clients({\n options = { useStringArrays: true, deps: true },\n state,\n}: {\n options?: OAuth2ClientExportOptions;\n state: State;\n}): Promise<OAuth2ClientExportInterface> {\n debugMessage({\n message: `OAuth2ClientOps.exportOAuth2Clients: start`,\n state,\n });\n const exportData = createOAuth2ClientExportTemplate({ state });\n const errors = [];\n try {\n const provider = await getOAuth2Provider({ state });\n const clients = await getOAuth2Clients({ state });\n for (const client of clients) {\n try {\n client._provider = provider;\n exportData.application[client._id] = client;\n if (options.deps) {\n await exportOAuth2ClientDependencies(\n client,\n options,\n exportData,\n state\n );\n }\n } catch (error) {\n errors.push(error);\n }\n }\n } catch (error) {\n errors.push(error);\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Export error:\\n${errorMessages}`);\n }\n debugMessage({ message: `OAuth2ClientOps.exportOAuth2Clients: end`, state });\n return exportData;\n}\n\n/**\n * Export OAuth2 client by ID\n * @param {string} clientId oauth2 client id\n * @param {OAuth2ClientExportOptions} options export options\n * @returns {OAuth2ClientExportInterface} export data\n */\nexport async function exportOAuth2Client({\n clientId,\n options = { useStringArrays: true, deps: true },\n state,\n}: {\n clientId: string;\n options?: OAuth2ClientExportOptions;\n state: State;\n}): Promise<OAuth2ClientExportInterface> {\n debugMessage({ message: `OAuth2ClientOps.exportOAuth2Client: start`, state });\n const exportData = createOAuth2ClientExportTemplate({ state });\n const errors = [];\n try {\n const clientData = await getOAuth2Client({ clientId, state });\n clientData._provider = await getOAuth2Provider({ state });\n exportData.application[clientData._id] = clientData;\n if (options.deps) {\n await exportOAuth2ClientDependencies(\n clientData,\n options,\n exportData,\n state\n );\n }\n } catch (error) {\n errors.push(error);\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Export error:\\n${errorMessages}`);\n }\n debugMessage({ message: `OAuth2ClientOps.exportOAuth2Client: end`, state });\n return exportData;\n}\n\n/**\n * Helper function to export dependencies of an OAuth2 Client\n * @param {unknown} clientData oauth2 client data\n * @param {OAuth2ClientExportInterface} importData import data\n */\nasync function importOAuth2ClientDependencies(\n clientData: unknown,\n importData: OAuth2ClientExportInterface,\n state: State\n) {\n for (const key of Object.keys(clientData['overrideOAuth2ClientConfig'])) {\n if (key.endsWith('Script')) {\n const scriptId = clientData['overrideOAuth2ClientConfig'][key];\n if (scriptId !== '[Empty]' && importData.script[scriptId]) {\n const scriptData: ScriptSkeleton = importData.script[scriptId];\n await putScript({ scriptId, scriptData, state });\n }\n }\n }\n}\n\n/**\n * Import OAuth2 Client by ID\n * @param {string} clientId client id\n * @param {OAuth2ClientExportInterface} importData import data\n * @param {OAuth2ClientImportOptions} options import options\n */\nexport async function importOAuth2Client({\n clientId,\n importData,\n options = { deps: true },\n state,\n}: {\n clientId: string;\n importData: OAuth2ClientExportInterface;\n options?: OAuth2ClientImportOptions;\n state: State;\n}) {\n let response = null;\n const errors = [];\n const imported = [];\n for (const id of Object.keys(importData.application)) {\n if (id === clientId) {\n try {\n const clientData = importData.application[id];\n delete clientData._provider;\n delete clientData._rev;\n if (options.deps) {\n await importOAuth2ClientDependencies(clientData, importData, state);\n }\n response = await putOAuth2Client({ clientId: id, clientData, state });\n imported.push(id);\n } catch (error) {\n errors.push(error);\n }\n }\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Import error:\\n${errorMessages}`);\n }\n if (0 === imported.length) {\n throw new Error(`Import error:\\n${clientId} not found in import data!`);\n }\n return response;\n}\n\n/**\n * Import first OAuth2 Client\n * @param {OAuth2ClientExportInterface} importData import data\n * @param {OAuth2ClientImportOptions} options import options\n */\nexport async function importFirstOAuth2Client({\n importData,\n options = { deps: true },\n state,\n}: {\n importData: OAuth2ClientExportInterface;\n options?: OAuth2ClientImportOptions;\n state: State;\n}) {\n let response = null;\n const errors = [];\n const imported = [];\n for (const id of Object.keys(importData.application)) {\n try {\n const clientData = importData.application[id];\n delete clientData._provider;\n delete clientData._rev;\n if (options.deps) {\n await importOAuth2ClientDependencies(clientData, importData, state);\n }\n response = await putOAuth2Client({ clientId: id, clientData, state });\n imported.push(id);\n } catch (error) {\n errors.push(error);\n }\n break;\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Import error:\\n${errorMessages}`);\n }\n if (0 === imported.length) {\n throw new Error(`Import error:\\nNo clients found in import data!`);\n }\n return response;\n}\n\n/**\n * Import OAuth2 Clients\n * @param {OAuth2ClientExportInterface} importData import data\n * @param {OAuth2ClientImportOptions} options import options\n * @returns {Promise<unknown[]>} array of imported oauth2 clients\n */\nexport async function importOAuth2Clients({\n importData,\n options = { deps: true },\n state,\n}: {\n importData: OAuth2ClientExportInterface;\n options?: OAuth2ClientImportOptions;\n state: State;\n}): Promise<unknown[]> {\n const response = [];\n const errors = [];\n const imported = [];\n for (const id of Object.keys(importData.application)) {\n try {\n const clientData = importData.application[id];\n delete clientData._provider;\n delete clientData._rev;\n if (options.deps) {\n await importOAuth2ClientDependencies(clientData, importData, state);\n }\n response.push(await putOAuth2Client({ clientId: id, clientData, state }));\n imported.push(id);\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Import error:\\n${errorMessages}`);\n }\n if (0 === imported.length) {\n throw new Error(`Import error:\\nNo clients found in import data!`);\n }\n return response;\n}\n"]}
@@ -88,18 +88,8 @@ export interface ScriptExportInterface {
88
88
  meta?: ExportMetaData;
89
89
  script: Record<string, ScriptSkeleton>;
90
90
  }
91
- export declare enum NodeClassification {
92
- STANDARD = "standard",
93
- CUSTOM = "custom",
94
- CLOUD = "cloud",
95
- PREMIUM = "premium"
96
- }
97
- export declare enum JourneyClassification {
98
- STANDARD = "standard",
99
- CUSTOM = "custom",
100
- CLOUD = "cloud",
101
- PREMIUM = "premium"
102
- }
91
+ export type NodeClassificationType = 'standard' | 'custom' | 'cloud' | 'premium';
92
+ export type JourneyClassificationType = 'standard' | 'custom' | 'cloud' | 'premium';
103
93
  export interface MultiOpStatusInterface {
104
94
  total: number;
105
95
  successes: number;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ops/OpsTypes.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,aAAa,EACb,iBAAiB,EACjB,qBAAqB,EACrB,qBAAqB,EACrB,YAAY,EACZ,qBAAqB,EACrB,cAAc,EACd,iBAAiB,EACjB,aAAa,EACb,YAAY,EACb,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,MAAM,iBAAiB,CAAC;AAEpC;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC;;OAEG;IACH,eAAe,EAAE,OAAO,CAAC;IACzB;;OAEG;IACH,IAAI,EAAE,OAAO,CAAC;CACf;AAED;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC;;OAEG;IACH,MAAM,EAAE,OAAO,CAAC;IAChB;;OAEG;IACH,IAAI,EAAE,OAAO,CAAC;CACf;AAED,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,eAAe,EAAE,MAAM,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,iBAAiB,EAAE,MAAM,CAAC;CAC3B;AAED,MAAM,WAAW,yBAAyB;IACxC,IAAI,CAAC,EAAE,cAAc,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;IAC1C,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;IAC1C,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,Y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ml2ProviderSkeleton,\n ScriptSkeleton,\n SocialIdpSkeleton,\n ThemeSkeleton,\n TreeSkeleton,\n} from '../api/ApiTypes';\nimport State from '../shared/State';\n\n/**\n * Tree export options\n */\nexport interface TreeExportOptions {\n /**\n * Where applicable, use string arrays to store multi-line text (e.g. scripts).\n */\n useStringArrays: boolean;\n /**\n * Include any dependencies (scripts, email templates, SAML entity providers and circles of trust, social identity providers, themes).\n */\n deps: boolean;\n}\n\n/**\n * Tree import options\n */\nexport interface TreeImportOptions {\n /**\n * Generate new UUIDs for all nodes during import.\n */\n reUuid: boolean;\n /**\n * Include any dependencies (scripts, email templates, SAML entity providers and circles of trust, social identity providers, themes).\n */\n deps: boolean;\n}\n\nexport interface ExportMetaData {\n origin: string;\n originAmVersion: string;\n exportedBy: string;\n exportDate: string;\n exportTool: string;\n exportToolVersion: string;\n}\n\nexport interface SingleTreeExportInterface {\n meta?: ExportMetaData;\n innerNodes?: Record<string, NodeSkeleton>;\n innernodes?: Record<string, NodeSkeleton>;\n nodes: Record<string, NodeSkeleton>;\n scripts: Record<string, ScriptSkeleton>;\n emailTemplates: Record<string, EmailTemplateSkeleton>;\n socialIdentityProviders: Record<string, SocialIdpSkeleton>;\n themes: ThemeSkeleton[];\n saml2Entities: Record<string, Saml2ProviderSkeleton>;\n circlesOfTrust: Record<string, CircleOfTrustSkeleton>;\n tree: TreeSkeleton;\n}\n\nexport interface MultiTreeExportInterface {\n meta?: ExportMetaData;\n trees: Record<string, SingleTreeExportInterface>;\n}\n\nexport interface AgentExportInterface {\n meta?: Record<string, ExportMetaData>;\n agents: Record<string, AgentSkeleton>;\n}\n\nexport interface CirclesOfTrustExportInterface {\n meta?: ExportMetaData;\n script: Record<string, ScriptSkeleton>;\n saml: {\n hosted: Record<string, Saml2ProviderSkeleton>;\n remote: Record<string, Saml2ProviderSkeleton>;\n metadata: Record<string, string[]>;\n cot: Record<string, CircleOfTrustSkeleton>;\n };\n}\n\nexport interface Saml2ExportInterface {\n meta?: ExportMetaData;\n script: Record<string, ScriptSkeleton>;\n saml: {\n hosted: Record<string, Saml2ProviderSkeleton>;\n remote: Record<string, Saml2ProviderSkeleton>;\n metadata: Record<string, string[]>;\n };\n}\n\nexport interface ServiceExportInterface {\n meta?: Record<string, ExportMetaData>;\n service: Record<string, AmServiceSkeleton>;\n}\n\nexport interface TreeDependencyMapInterface {\n [k: string]: TreeDependencyMapInterface[];\n}\n\nexport interface TreeExportResolverInterface {\n (treeId: string, state: State): Promise<SingleTreeExportInterface>;\n}\n\nexport interface ScriptExportInterface {\n meta?: ExportMetaData;\n script: Record<string, ScriptSkeleton>;\n}\n\nexport enum NodeClassification {\n STANDARD = 'standard',\n CUSTOM = 'custom',\n CLOUD = 'cloud',\n PREMIUM = 'premium',\n}\n\nexport enum JourneyClassification {\n STANDARD = 'standard',\n CUSTOM = 'custom',\n CLOUD = 'cloud',\n PREMIUM = 'premium',\n}\n\nexport interface MultiOpStatusInterface {\n total: number;\n successes: number;\n warnings: number;\n failures: number;\n message?: string;\n}\n"]}
1
+ {"version":3,"sources":["../src/ops/OpsTypes.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,aAAa,EACb,iBAAiB,EACjB,qBAAqB,EACrB,qBAAqB,EACrB,YAAY,EACZ,qBAAqB,EACrB,cAAc,EACd,iBAAiB,EACjB,aAAa,EACb,YAAY,EACb,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,MAAM,iBAAiB,CAAC;AAEpC;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC;;OAEG;IACH,eAAe,EAAE,OAAO,CAAC;IACzB;;OAEG;IACH,IAAI,EAAE,OAAO,CAAC;CACf;AAED;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC;;OAEG;IACH,MAAM,EAAE,OAAO,CAAC;IAChB;;OAEG;IACH,IAAI,EAAE,OAAO,CAAC;CACf;AAED,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,eAAe,EAAE,MAAM,CAAC;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OAAO,GACP,SAAS,CAAC;AAEd,MAAM,WAAW,sBAAsB;IACrC,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB","file":"OpsTypes.d.ts","sourcesContent":["import {\n AgentSkeleton,\n AmServiceSkeleton,\n CircleOfTrustSkeleton,\n EmailTemplateSkeleton,\n NodeSkeleton,\n Saml2ProviderSkeleton,\n ScriptSkeleton,\n SocialIdpSkeleton,\n ThemeSkeleton,\n TreeSkeleton,\n} from '../api/ApiTypes';\nimport State from '../shared/State';\n\n/**\n * Tree export options\n */\nexport interface TreeExportOptions {\n /**\n * Where applicable, use string arrays to store multi-line text (e.g. scripts).\n */\n useStringArrays: boolean;\n /**\n * Include any dependencies (scripts, email templates, SAML entity providers and circles of trust, social identity providers, themes).\n */\n deps: boolean;\n}\n\n/**\n * Tree import options\n */\nexport interface TreeImportOptions {\n /**\n * Generate new UUIDs for all nodes during import.\n */\n reUuid: boolean;\n /**\n * Include any dependencies (scripts, email templates, SAML entity providers and circles of trust, social identity providers, themes).\n */\n deps: boolean;\n}\n\nexport interface ExportMetaData {\n origin: string;\n originAmVersion: string;\n exportedBy: string;\n exportDate: string;\n exportTool: string;\n exportToolVersion: string;\n}\n\nexport interface SingleTreeExportInterface {\n meta?: ExportMetaData;\n innerNodes?: Record<string, NodeSkeleton>;\n innernodes?: Record<string, NodeSkeleton>;\n nodes: Record<string, NodeSkeleton>;\n scripts: Record<string, ScriptSkeleton>;\n emailTemplates: Record<string, EmailTemplateSkeleton>;\n socialIdentityProviders: Record<string, SocialIdpSkeleton>;\n themes: ThemeSkeleton[];\n saml2Entities: Record<string, Saml2ProviderSkeleton>;\n circlesOfTrust: Record<string, CircleOfTrustSkeleton>;\n tree: TreeSkeleton;\n}\n\nexport interface MultiTreeExportInterface {\n meta?: ExportMetaData;\n trees: Record<string, SingleTreeExportInterface>;\n}\n\nexport interface AgentExportInterface {\n meta?: Record<string, ExportMetaData>;\n agents: Record<string, AgentSkeleton>;\n}\n\nexport interface CirclesOfTrustExportInterface {\n meta?: ExportMetaData;\n script: Record<string, ScriptSkeleton>;\n saml: {\n hosted: Record<string, Saml2ProviderSkeleton>;\n remote: Record<string, Saml2ProviderSkeleton>;\n metadata: Record<string, string[]>;\n cot: Record<string, CircleOfTrustSkeleton>;\n };\n}\n\nexport interface Saml2ExportInterface {\n meta?: ExportMetaData;\n script: Record<string, ScriptSkeleton>;\n saml: {\n hosted: Record<string, Saml2ProviderSkeleton>;\n remote: Record<string, Saml2ProviderSkeleton>;\n metadata: Record<string, string[]>;\n };\n}\n\nexport interface ServiceExportInterface {\n meta?: Record<string, ExportMetaData>;\n service: Record<string, AmServiceSkeleton>;\n}\n\nexport interface TreeDependencyMapInterface {\n [k: string]: TreeDependencyMapInterface[];\n}\n\nexport interface TreeExportResolverInterface {\n (treeId: string, state: State): Promise<SingleTreeExportInterface>;\n}\n\nexport interface ScriptExportInterface {\n meta?: ExportMetaData;\n script: Record<string, ScriptSkeleton>;\n}\n\nexport type NodeClassificationType =\n | 'standard'\n | 'custom'\n | 'cloud'\n | 'premium';\n\nexport type JourneyClassificationType =\n | 'standard'\n | 'custom'\n | 'cloud'\n | 'premium';\n\nexport interface MultiOpStatusInterface {\n total: number;\n successes: number;\n warnings: number;\n failures: number;\n message?: string;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ops/OrganizationOps.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,MAAM,iBAAiB,CAAC;AAGpC,MAAM,CAAC,OAAO,OAAO,eAAe;IAClC,KAAK,EAAE,KAAK,CAAC;gBACD,KAAK,EAAE,KAAK;IAIxB;;;OAGG;IACH,2BAA2B;IAI3B;;;OAGG;IACG,gBAAgB;CAGvB;AAED;;;GAGG;AACH,wBAAgB,2BAA2B,CAAC,EAAE,KAAK,EAAE,EAAE;IAAE,KAAK,EAAE,KAAK,CAAA;CAAE,UAMtE;AAED;;;GAGG;AACH,wBAAsB,gBAAgB,CAAC,EAAE,KAAK,EAAE,EAAE;IAAE,KAAK,EAAE,KAAK,CAAA;CAAE,kBAqCjE;AAGD,wBAAsB,wBAAwB,CAAC,EAAE,KAAK,EAAE,EAAE;IAAE,KAAK,EAAE,KAAK,CAAA;CAAE,kBAgCzE","file":"OrganizationOps.d.ts","sourcesContent":["import { queryAllManagedObjectsByType } from '../api/IdmConfigApi';\nimport State from '../shared/State';\nimport { printMessage } from './utils/Console';\n\nexport default class OrganizationOps {\n state: State;\n constructor(state: State) {\n this.state = state;\n }\n\n /**\n * Get organization managed object type\n * @returns {String} organization managed object type in this realm\n */\n getRealmManagedOrganization() {\n return getRealmManagedOrganization({ state: this.state });\n }\n\n /**\n * Get organizations\n * @returns {Promise} promise resolving to an object containing an array of organization objects\n */\n async getOrganizations() {\n return getOrganizations({ state: this.state });\n }\n}\n\n/**\n * Get organization managed object type\n * @returns {String} organization managed object type in this realm\n */\nexport function getRealmManagedOrganization({ state }: { state: State }) {\n let realmManagedOrg = 'organization';\n if (state.getDeploymentType() === global.CLOUD_DEPLOYMENT_TYPE_KEY) {\n realmManagedOrg = `${state.getRealm()}_organization`;\n }\n return realmManagedOrg;\n}\n\n/**\n * Get organizations\n * @returns {Promise} promise resolving to an object containing an array of organization objects\n */\nexport async function getOrganizations({ state }: { state: State }) {\n const orgs = [];\n let result = {\n result: [],\n resultCount: 0,\n pagedResultsCookie: null,\n totalPagedResultsPolicy: 'NONE',\n totalPagedResults: -1,\n remainingPagedResults: -1,\n };\n try {\n do {\n try {\n // eslint-disable-next-line no-await-in-loop\n result = await queryAllManagedObjectsByType({\n type: getRealmManagedOrganization({ state }),\n fields: ['name', 'parent/*/name', 'children/*/name'],\n pageCookie: result.pagedResultsCookie,\n state,\n });\n } catch (queryAllManagedObjectsByTypeError) {\n printMessage(queryAllManagedObjectsByTypeError, 'error');\n printMessage(\n `Error querying ${getRealmManagedOrganization({\n state,\n })} objects: ${queryAllManagedObjectsByTypeError}`,\n 'error'\n );\n }\n orgs.concat(result.result);\n printMessage('.', 'text', false);\n } while (result.pagedResultsCookie);\n } catch (error) {\n printMessage(error.response.data, 'error');\n printMessage(`Error retrieving all organizations: ${error}`, 'error');\n }\n return orgs;\n}\n\n// unfinished work\nexport async function listOrganizationsTopDown({ state }: { state: State }) {\n const orgs = [];\n let result = {\n result: [],\n resultCount: 0,\n pagedResultsCookie: null,\n totalPagedResultsPolicy: 'NONE',\n totalPagedResults: -1,\n remainingPagedResults: -1,\n };\n do {\n try {\n // eslint-disable-next-line no-await-in-loop\n result = await queryAllManagedObjectsByType({\n type: getRealmManagedOrganization({ state }),\n fields: ['name', 'parent/*/name', 'children/*/name'],\n pageCookie: result.pagedResultsCookie,\n state,\n });\n } catch (queryAllManagedObjectsByTypeError) {\n printMessage(queryAllManagedObjectsByTypeError, 'error');\n printMessage(\n `Error querying ${getRealmManagedOrganization({\n state,\n })} objects: ${queryAllManagedObjectsByTypeError}`,\n 'error'\n );\n }\n orgs.concat(result.result);\n printMessage('.', 'text', false);\n } while (result.pagedResultsCookie);\n return orgs;\n}\n"]}
1
+ {"version":3,"sources":["../src/ops/OrganizationOps.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,MAAM,iBAAiB,CAAC;AAGpC,MAAM,CAAC,OAAO,OAAO,eAAe;IAClC,KAAK,EAAE,KAAK,CAAC;gBACD,KAAK,EAAE,KAAK;IAIxB;;;OAGG;IACH,2BAA2B;IAI3B;;;OAGG;IACG,gBAAgB;CAGvB;AAED;;;GAGG;AACH,wBAAgB,2BAA2B,CAAC,EAAE,KAAK,EAAE,EAAE;IAAE,KAAK,EAAE,KAAK,CAAA;CAAE,UAMtE;AAED;;;GAGG;AACH,wBAAsB,gBAAgB,CAAC,EAAE,KAAK,EAAE,EAAE;IAAE,KAAK,EAAE,KAAK,CAAA;CAAE,kBA8CjE;AAGD,wBAAsB,wBAAwB,CAAC,EAAE,KAAK,EAAE,EAAE;IAAE,KAAK,EAAE,KAAK,CAAA;CAAE,kBAqCzE","file":"OrganizationOps.d.ts","sourcesContent":["import { queryAllManagedObjectsByType } from '../api/IdmConfigApi';\nimport State from '../shared/State';\nimport { printMessage } from './utils/Console';\n\nexport default class OrganizationOps {\n state: State;\n constructor(state: State) {\n this.state = state;\n }\n\n /**\n * Get organization managed object type\n * @returns {String} organization managed object type in this realm\n */\n getRealmManagedOrganization() {\n return getRealmManagedOrganization({ state: this.state });\n }\n\n /**\n * Get organizations\n * @returns {Promise} promise resolving to an object containing an array of organization objects\n */\n async getOrganizations() {\n return getOrganizations({ state: this.state });\n }\n}\n\n/**\n * Get organization managed object type\n * @returns {String} organization managed object type in this realm\n */\nexport function getRealmManagedOrganization({ state }: { state: State }) {\n let realmManagedOrg = 'organization';\n if (state.getDeploymentType() === global.CLOUD_DEPLOYMENT_TYPE_KEY) {\n realmManagedOrg = `${state.getRealm()}_organization`;\n }\n return realmManagedOrg;\n}\n\n/**\n * Get organizations\n * @returns {Promise} promise resolving to an object containing an array of organization objects\n */\nexport async function getOrganizations({ state }: { state: State }) {\n const orgs = [];\n let result = {\n result: [],\n resultCount: 0,\n pagedResultsCookie: null,\n totalPagedResultsPolicy: 'NONE',\n totalPagedResults: -1,\n remainingPagedResults: -1,\n };\n try {\n do {\n try {\n // eslint-disable-next-line no-await-in-loop\n result = await queryAllManagedObjectsByType({\n type: getRealmManagedOrganization({ state }),\n fields: ['name', 'parent/*/name', 'children/*/name'],\n pageCookie: result.pagedResultsCookie,\n state,\n });\n } catch (queryAllManagedObjectsByTypeError) {\n printMessage({\n message: queryAllManagedObjectsByTypeError,\n type: 'error',\n state,\n });\n printMessage({\n message: `Error querying ${getRealmManagedOrganization({\n state,\n })} objects: ${queryAllManagedObjectsByTypeError}`,\n type: 'error',\n state,\n });\n }\n orgs.concat(result.result);\n printMessage({ message: '.', type: 'text', newline: false, state });\n } while (result.pagedResultsCookie);\n } catch (error) {\n printMessage({ message: error.response.data, type: 'error', state });\n printMessage({\n message: `Error retrieving all organizations: ${error}`,\n type: 'error',\n state,\n });\n }\n return orgs;\n}\n\n// unfinished work\nexport async function listOrganizationsTopDown({ state }: { state: State }) {\n const orgs = [];\n let result = {\n result: [],\n resultCount: 0,\n pagedResultsCookie: null,\n totalPagedResultsPolicy: 'NONE',\n totalPagedResults: -1,\n remainingPagedResults: -1,\n };\n do {\n try {\n // eslint-disable-next-line no-await-in-loop\n result = await queryAllManagedObjectsByType({\n type: getRealmManagedOrganization({ state }),\n fields: ['name', 'parent/*/name', 'children/*/name'],\n pageCookie: result.pagedResultsCookie,\n state,\n });\n } catch (queryAllManagedObjectsByTypeError) {\n printMessage({\n message: queryAllManagedObjectsByTypeError,\n type: 'error',\n state,\n });\n printMessage({\n message: `Error querying ${getRealmManagedOrganization({\n state,\n })} objects: ${queryAllManagedObjectsByTypeError}`,\n type: 'error',\n state,\n });\n }\n orgs.concat(result.result);\n printMessage({ message: '.', type: 'text', newline: false, state });\n } while (result.pagedResultsCookie);\n return orgs;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ops/PolicyOps.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,SAAS,EACT,SAAS,EACT,YAAY,EACb,MAAM,oBAAoB,CAAC;AAG5B,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,EACL,eAAe,EAEf,iBAAiB,EACjB,cAAc,EACd,oBAAoB,EACpB,cAAc,EACf,MAAM,iBAAiB,CAAC;AAMzB,OAAO,KAAK,MAAM,iBAAiB,CAAC;AAEpC,MAAM,CAAC,OAAO,OAAO,SAAS;IAC5B,KAAK,EAAE,KAAK,CAAC;gBACD,KAAK,EAAE,KAAK;IAIxB;;;OAGG;IACG,WAAW,IAAI,OAAO,CAAC,cAAc,EAAE,CAAC;IAI9C;;;;OAIG;IACG,sBAAsB,CAAC,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,EAAE,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C,OAIC,EACD,KAAK,GACN,EAAE;IACD,OAAO,CAAC,EAAE,mBAAmB,CAAC;IAC9B,KAAK,EAAE,KAAK,CAAC;CACd,GAAG,OAAO,CAAC,qBAAqB,CAAC,CAqCjC;AAED;;;;;GAKG;AACH,wBAAsB,yBAAyB,CAAC,EAC9C,aAAa,EACb,OAIC,EACD,KAAK,GACN,EAAE;IACD,aAAa,EAAE,MAAM,CAAC;IACtB,OAAO,CAAC,EAAE,mBAAmB,CAAC;IAC9B,KAAK,EAAE,KAAK,CAAC;CACd,GAAG,OAAO,CAAC,qBAAqB,CAAC,CAwCjC;AA0HD;;;;;;GAMG;AACH,wBAAsB,YAAY,CAAC,EACjC,QAAQ,EACR,UAAU,EACV,OAAwC,EACxC,KAAK,GACN,EAAE;IACD,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,qBAAqB,CAAC;IAClC,OAAO,CAAC,EAAE,mBAAmB,CAAC;IAC9B,KAAK,EAAE,KAAK,CAAC;CACd,GAAG,OAAO,CAAC,cAAc,CAAC,CA2D1B;AAED;;;;;GAKG;AACH,wBAAsB,iBAAiB,CAAC,EACtC,UAAU,EACV,OAAwC,EACxC,KAAK,GACN,EAAE;IACD,UAAU,EAAE,qBAAqB,CAAC;IAClC,OAAO,CAAC,EAAE,mBAAmB,CAAC;IAC9B,KAAK,EAAE,KAAK,CAAC;CACd,GAAG,OAAO,CAAC,cAAc,CAAC,CA0D1B;AAED;;;;;GAKG;AACH,wBAAsB,cAAc,CAAC,EACnC,UAAU,EACV,OAAwC,EACxC,KAAK,GACN,EAAE;IACD,UAAU,EAAE,qBAAqB,CAAC;IAClC,OAAO,CAAC,EAAE,mBAAmB,CAAC;IAC9B,KAAK,EAAE,KAAK,CAAC;CACd,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC,CAuD5B","file":"PolicyOps.d.ts","sourcesContent":["import {\n getPolicies as _getPolicies,\n getPoliciesByPolicySet as _getPoliciesByPolicySet,\n getPolicy,\n putPolicy,\n deletePolicy,\n} from '../api/PoliciesApi';\nimport { getScript, putScript } from './ScriptOps';\nimport { convertBase64TextToArray } from './utils/ExportImportUtils';\nimport { ExportMetaData } from './OpsTypes';\nimport {\n PolicyCondition,\n PolicyConditionType,\n PolicySetSkeleton,\n PolicySkeleton,\n ResourceTypeSkeleton,\n ScriptSkeleton,\n} from '../api/ApiTypes';\nimport { getMetadata } from './utils/ExportImportUtils';\nimport { debugMessage } from './utils/Console';\nimport { getResourceType } from '../api/ResourceTypesApi';\nimport { createPolicySet, getPolicySet, updatePolicySet } from './PolicySetOps';\nimport { createResourceType, updateResourceType } from './ResourceTypeOps';\nimport State from '../shared/State';\n\nexport default class PolicyOps {\n state: State;\n constructor(state: State) {\n this.state = state;\n }\n\n /**\n * Get all policies\n * @returns {Promise<PolicySkeleton>} a promise that resolves to an array of policy set objects\n */\n async getPolicies(): Promise<PolicySkeleton[]> {\n return getPolicies({ state: this.state });\n }\n\n /**\n * Get policies by policy set\n * @param {string} policySetId policy set id/name\n * @returns {Promise<PolicySkeleton[]>} a promise resolving to an array of policy objects\n */\n async getPoliciesByPolicySet(policySetId: string): Promise<PolicySkeleton[]> {\n return getPoliciesByPolicySet({ policySetId, state: this.state });\n }\n\n async getPolicy(policyId: string) {\n return getPolicy({ policyId, state: this.state });\n }\n\n async putPolicy(policyId: string, policyData: PolicySkeleton) {\n return putPolicy({ policyId, policyData, state: this.state });\n }\n\n async deletePolicy(policyId: string) {\n return deletePolicy({ policyId, state: this.state });\n }\n\n /**\n * Export policy\n * @param {string} policyId policy id/name\n * @returns {Promise<PolicyExportInterface>} a promise that resolves to a PolicyExportInterface object\n */\n async exportPolicy(\n policyId: string,\n options: PolicyExportOptions = {\n deps: true,\n prereqs: false,\n useStringArrays: true,\n }\n ): Promise<PolicyExportInterface> {\n return exportPolicy({ policyId, options, state: this.state });\n }\n\n /**\n * Export policies\n * @param {PolicyExportOptions} options export options\n * @returns {Promise<PolicyExportInterface>} a promise that resolves to an PolicyExportInterface object\n */\n async exportPolicies(\n options: PolicyExportOptions = {\n deps: true,\n prereqs: false,\n useStringArrays: true,\n }\n ): Promise<PolicyExportInterface> {\n return exportPolicies({ options, state: this.state });\n }\n\n /**\n * Export policies by policy set\n * @param {string} policySetName policy set id/name\n * @param {PolicyExportOptions} options export options\n * @returns {Promise<PolicyExportInterface>} a promise that resolves to an PolicyExportInterface object\n */\n async exportPoliciesByPolicySet(\n policySetName: string,\n options: PolicyExportOptions = {\n deps: true,\n prereqs: false,\n useStringArrays: true,\n }\n ): Promise<PolicyExportInterface> {\n return exportPoliciesByPolicySet({\n policySetName,\n options,\n state: this.state,\n });\n }\n\n /**\n * Import policy by id\n * @param {string} policyId policy id\n * @param {PolicyExportInterface} importData import data\n * @param {PolicyImportOptions} options import options\n * @returns {Promise<PolicySkeleton>} imported policy object\n */\n async importPolicy(\n policyId: string,\n importData: PolicyExportInterface,\n options: PolicyImportOptions = { deps: true, prereqs: false }\n ): Promise<PolicySkeleton> {\n return importPolicy({ policyId, importData, options, state: this.state });\n }\n\n /**\n * Import first policy\n * @param {PolicyExportInterface} importData import data\n * @param {PolicyImportOptions} options import options\n * @returns {Promise<PolicySkeleton>} imported policy object\n */\n async importFirstPolicy(\n importData: PolicyExportInterface,\n options: PolicyImportOptions = { deps: true, prereqs: false }\n ): Promise<PolicySkeleton> {\n return importFirstPolicy({ importData, options, state: this.state });\n }\n\n /**\n * Import policies\n * @param {PolicyExportInterface} importData import data\n * @param {PolicyImportOptions} options import options\n * @returns {Promise<PolicySkeleton[]>} array of imported policy objects\n */\n async importPolicies(\n importData: PolicyExportInterface,\n options: PolicyImportOptions = { deps: true, prereqs: false }\n ): Promise<PolicySkeleton[]> {\n return importPolicies({ importData, options, state: this.state });\n }\n}\n\nexport interface PolicyExportInterface {\n meta?: ExportMetaData;\n script: Record<string, ScriptSkeleton>;\n resourcetype: Record<string, ResourceTypeSkeleton>;\n policy: Record<string, PolicySkeleton>;\n policyset: Record<string, PolicySetSkeleton>;\n}\n\n/**\n * Policy export options\n */\nexport interface PolicyExportOptions {\n /**\n * Include any dependencies (scripts).\n */\n deps: boolean;\n /**\n * Include any prerequisites (policy sets, resource types).\n */\n prereqs: boolean;\n /**\n * Use string arrays to store multi-line text in scripts.\n */\n useStringArrays: boolean;\n}\n\n/**\n * Policy import options\n */\nexport interface PolicyImportOptions {\n /**\n * Include any dependencies (scripts).\n */\n deps: boolean;\n /**\n * Include any prerequisites (policy sets, resource types).\n */\n prereqs: boolean;\n /**\n * Import policies into different policy set\n */\n policySetName?: string;\n}\n\n/**\n * Create an empty export template\n * @returns {PolicyExportInterface} an empty export template\n */\nfunction createPolicyExportTemplate({\n state,\n}: {\n state: State;\n}): PolicyExportInterface {\n return {\n meta: getMetadata({ state }),\n script: {},\n policy: {},\n resourcetype: {},\n policyset: {},\n } as PolicyExportInterface;\n}\n\n/**\n * Get all policies\n * @returns {Promise<PolicySkeleton>} a promise that resolves to an array of policy set objects\n */\nexport async function getPolicies({\n state,\n}: {\n state: State;\n}): Promise<PolicySkeleton[]> {\n const { result } = await _getPolicies({ state });\n return result;\n}\n\n/**\n * Get policies by policy set\n * @param {string} policySetId policy set id/name\n * @returns {Promise<PolicySkeleton[]>} a promise resolving to an array of policy objects\n */\nexport async function getPoliciesByPolicySet({\n policySetId,\n state,\n}: {\n policySetId: string;\n state: State;\n}): Promise<PolicySkeleton[]> {\n const data = await _getPoliciesByPolicySet({ policySetId, state });\n return data.result;\n}\n\nexport { getPolicy, putPolicy, deletePolicy };\n\n/**\n * Find all script references in a deeply-nested policy condition object\n * @param {PolicyCondition} condition condition object\n * @returns {string[]} array of script UUIDs\n * \n * Sample condition block:\n * \n \"condition\": {\n \"type\": \"AND\",\n \"conditions\": [\n {\n \"type\": \"Script\",\n \"scriptId\": \"62f18ede-e5e7-4a7b-8b73-1b02fcbd241a\"\n },\n {\n \"type\": \"AuthenticateToService\",\n \"authenticateToService\": \"TxAuthz\"\n },\n {\n \"type\": \"OR\",\n \"conditions\": [\n {\n \"type\": \"Session\",\n \"maxSessionTime\": 5,\n \"terminateSession\": false\n },\n {\n \"type\": \"OAuth2Scope\",\n \"requiredScopes\": [\n \"openid\"\n ]\n },\n {\n \"type\": \"NOT\",\n \"condition\": {\n \"type\": \"Script\",\n \"scriptId\": \"729ee140-a4e9-43af-b358-d60eeda13cc3\"\n }\n }\n ]\n }\n ]\n },\n*/\nexport function findScriptUuids(condition: PolicyCondition): string[] {\n let scriptUuids: string[] = [];\n if (!condition) return scriptUuids;\n if (\n condition.type === PolicyConditionType.AND.toString() ||\n condition.type === PolicyConditionType.OR.toString() ||\n condition.type === PolicyConditionType.NOT.toString()\n ) {\n // single condition\n if (condition.condition) {\n scriptUuids.push(...findScriptUuids(condition.condition));\n }\n // array of conditions\n if (condition.conditions) {\n for (const cond of condition.conditions) {\n scriptUuids.push(...findScriptUuids(cond));\n }\n }\n } else if (condition.type === PolicyConditionType.Script.toString()) {\n scriptUuids.push(condition.scriptId as string);\n }\n // de-duplicate\n scriptUuids = [...new Set(scriptUuids)];\n return scriptUuids;\n}\n\n/**\n * Get scripts for a policy object\n * @param {PolicySkeleton} policyData policy object\n * @returns {Promise<ScriptSkeleton[]>} a promise that resolves to an array of script objects\n */\nexport async function getScripts({\n policyData,\n state,\n}: {\n policyData: PolicySkeleton;\n state: State;\n}): Promise<ScriptSkeleton[]> {\n debugMessage(`PolicyOps.getScripts: start [policy=${policyData['name']}]`);\n const errors = [];\n const scripts = [];\n try {\n const scriptUuids = findScriptUuids(policyData.condition);\n debugMessage(`found scripts: ${scriptUuids}`);\n for (const scriptUuid of scriptUuids) {\n try {\n const script = await getScript({ scriptId: scriptUuid, state });\n scripts.push(script);\n } catch (error) {\n error.message = `Error retrieving script ${scriptUuid} referenced in policy ${policyData['name']}: ${error.message}`;\n errors.push(error);\n }\n }\n } catch (error) {\n error.message = `Error finding scripts in policy ${policyData['name']}: ${error.message}`;\n errors.push(error);\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Export error:\\n${errorMessages}`);\n }\n debugMessage(`PolicySetOps.getScripts: end`);\n return scripts;\n}\n\n/**\n * Helper function to export dependencies of a policy set\n * @param {PolicySkeleton} policyData policy set data\n * @param {PolicyExportInterface} exportData export data\n */\nasync function exportPolicyPrerequisites({\n policyData,\n exportData,\n state,\n}: {\n policyData: PolicySkeleton;\n exportData: PolicyExportInterface;\n state: State;\n}) {\n debugMessage(\n `PolicyOps.exportPolicyPrerequisites: start [policy=${policyData['name']}]`\n );\n // resource types\n if (policyData.resourceTypeUuid) {\n const resourceType = await getResourceType({\n resourceTypeUuid: policyData.resourceTypeUuid,\n state,\n });\n exportData.resourcetype[policyData.resourceTypeUuid] = resourceType;\n }\n // policy set\n if (policyData.applicationName) {\n const policySet = await getPolicySet({\n policySetName: policyData.applicationName,\n state,\n });\n exportData.policyset[policyData.applicationName] = policySet;\n }\n debugMessage(`PolicySetOps.exportPolicyPrerequisites: end`);\n}\n\n/**\n * Helper function to export dependencies of a policy set\n * @param {unknown} policyData policy set data\n * @param {PolicyExportOptions} options export options\n * @param {PolicyExportInterface} exportData export data\n */\nasync function exportPolicyDependencies({\n policyData,\n options,\n exportData,\n state,\n}: {\n policyData: PolicySkeleton;\n options: PolicyExportOptions;\n exportData: PolicyExportInterface;\n state: State;\n}) {\n debugMessage(\n `PolicyOps.exportPolicyDependencies: start [policy=${policyData['name']}]`\n );\n // scripts\n const scripts = await getScripts({ policyData, state });\n for (const scriptData of scripts) {\n if (options.useStringArrays) {\n scriptData.script = convertBase64TextToArray(scriptData.script as string);\n }\n exportData.script[scriptData._id] = scriptData;\n }\n debugMessage(`PolicySetOps.exportPolicySetDependencies: end`);\n}\n\n/**\n * Export policy\n * @param {string} policyId policy id/name\n * @returns {Promise<PolicyExportInterface>} a promise that resolves to a PolicyExportInterface object\n */\nexport async function exportPolicy({\n policyId,\n options = {\n deps: true,\n prereqs: false,\n useStringArrays: true,\n },\n state,\n}: {\n policyId: string;\n options?: PolicyExportOptions;\n state: State;\n}): Promise<PolicyExportInterface> {\n debugMessage(`PolicyOps.exportPolicy: start`);\n const policyData = await getPolicy({ policyId, state });\n const exportData = createPolicyExportTemplate({ state });\n exportData.policy[policyData._id] = policyData;\n if (options.prereqs) {\n await exportPolicyPrerequisites({ policyData, exportData, state });\n }\n if (options.deps) {\n await exportPolicyDependencies({ policyData, options, exportData, state });\n }\n debugMessage(`PolicyOps.exportPolicy: end`);\n return exportData;\n}\n\n/**\n * Export policies\n * @param {PolicyExportOptions} options export options\n * @returns {Promise<PolicyExportInterface>} a promise that resolves to an PolicyExportInterface object\n */\nexport async function exportPolicies({\n options = {\n deps: true,\n prereqs: false,\n useStringArrays: true,\n },\n state,\n}: {\n options?: PolicyExportOptions;\n state: State;\n}): Promise<PolicyExportInterface> {\n debugMessage(`PolicyOps.exportPolicies: start`);\n const exportData = createPolicyExportTemplate({ state });\n const errors = [];\n try {\n const policies = await getPolicies({ state });\n for (const policyData of policies) {\n exportData.policy[policyData._id] = policyData;\n if (options.prereqs) {\n try {\n await exportPolicyPrerequisites({ policyData, exportData, state });\n } catch (error) {\n errors.push(error);\n }\n }\n if (options.deps) {\n try {\n await exportPolicyDependencies({\n policyData,\n options,\n exportData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n }\n } catch (error) {\n errors.push(error);\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Export error:\\n${errorMessages}`);\n }\n debugMessage(`PolicyOps.exportPolicies: end`);\n return exportData;\n}\n\n/**\n * Export policies by policy set\n * @param {string} policySetName policy set id/name\n * @param {PolicyExportOptions} options export options\n * @returns {Promise<PolicyExportInterface>} a promise that resolves to an PolicyExportInterface object\n */\nexport async function exportPoliciesByPolicySet({\n policySetName,\n options = {\n deps: true,\n prereqs: false,\n useStringArrays: true,\n },\n state,\n}: {\n policySetName: string;\n options?: PolicyExportOptions;\n state: State;\n}): Promise<PolicyExportInterface> {\n debugMessage(`PolicyOps.exportPolicies: start`);\n const exportData = createPolicyExportTemplate({ state });\n const errors = [];\n try {\n const policies = await getPoliciesByPolicySet({\n policySetId: policySetName,\n state,\n });\n for (const policyData of policies) {\n exportData.policy[policyData._id] = policyData;\n if (options.prereqs) {\n try {\n await exportPolicyPrerequisites({ policyData, exportData, state });\n } catch (error) {\n errors.push(error);\n }\n }\n if (options.deps) {\n try {\n await exportPolicyDependencies({\n policyData,\n options,\n exportData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n }\n } catch (error) {\n errors.push(error);\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Export error:\\n${errorMessages}`);\n }\n debugMessage(`PolicyOps.exportPolicies: end`);\n return exportData;\n}\n\n/**\n * Helper function to import hard dependencies of a policy\n * @param {PolicySkeleton} policyData policy object\n * @param {PolicyExportInterface} exportData export data\n */\nasync function importPolicyPrerequisites({\n policyData,\n exportData,\n state,\n}: {\n policyData: PolicySkeleton;\n exportData: PolicyExportInterface;\n state: State;\n}) {\n debugMessage(\n `PolicyOps.importPolicyHardDependencies: start [policy=${policyData._id}]`\n );\n const errors = [];\n try {\n // resource type\n if (exportData.resourcetype[policyData.resourceTypeUuid]) {\n try {\n debugMessage(`Importing resource type ${policyData.resourceTypeUuid}`);\n await createResourceType({\n resourceTypeData:\n exportData.resourcetype[policyData.resourceTypeUuid],\n state,\n });\n } catch (error) {\n if (error.response?.status === 409)\n await updateResourceType({\n resourceTypeUuid: policyData.resourceTypeUuid,\n resourceTypeData:\n exportData.resourcetype[policyData.resourceTypeUuid],\n state,\n });\n else throw error;\n }\n }\n // policy set\n if (exportData.policyset[policyData.applicationName]) {\n try {\n debugMessage(`Importing policy set ${policyData.applicationName}`);\n await createPolicySet({\n policySetData: exportData.policyset[policyData.applicationName],\n state,\n });\n } catch (error) {\n if (error.response?.status === 409)\n await updatePolicySet({\n policySetData: exportData.policyset[policyData.applicationName],\n state,\n });\n else throw error;\n }\n }\n } catch (error) {\n error.message = `Error importing hard dependencies for policy ${\n policyData._id\n }: ${error.response?.data?.message || error.message}`;\n errors.push(error);\n }\n if (errors.length) {\n const errorMessages = errors\n .map((error) => error.response?.data?.message || error.message)\n .join('\\n');\n throw new Error(`Import hard dependencies error:\\n${errorMessages}`);\n }\n debugMessage(`PolicyOps.importPolicyHardDependencies: end`);\n}\n\n/**\n * Helper function to import soft dependencies of a policy\n * @param {PolicySkeleton} policyData policy object\n * @param {PolicyExportInterface} exportData export data\n */\nasync function importPolicyDependencies({\n policyData,\n exportData,\n state,\n}: {\n policyData: PolicySkeleton;\n exportData: PolicyExportInterface;\n state: State;\n}) {\n debugMessage(\n `PolicyOps.importPolicySoftDependencies: start [policy=${policyData._id}]`\n );\n const errors = [];\n try {\n // scripts\n const scriptUuids = findScriptUuids(policyData.condition);\n for (const scriptUuid of scriptUuids) {\n try {\n const scriptData = exportData.script[scriptUuid];\n debugMessage(`Importing script ${scriptUuid}`);\n await putScript({ scriptId: scriptUuid, scriptData, state });\n } catch (error) {\n debugMessage(error.response?.data);\n error.message = `Error importing script ${scriptUuid} for policy ${\n policyData._id\n }: ${error.response?.data?.message || error.message}`;\n errors.push(error);\n }\n }\n } catch (error) {\n error.message = `Error importing soft dependencies for policy ${\n policyData._id\n }: ${error.response?.data?.message || error.message}`;\n errors.push(error);\n }\n if (errors.length) {\n const errorMessages = errors\n .map((error) => error.response?.data?.message || error.message)\n .join('\\n');\n throw new Error(`Import soft dependencies error:\\n${errorMessages}`);\n }\n debugMessage(`PolicyOps.importPolicySoftDependencies: end`);\n}\n\n/**\n * Import policy by id\n * @param {string} policyId policy id\n * @param {PolicyExportInterface} importData import data\n * @param {PolicyImportOptions} options import options\n * @returns {Promise<PolicySkeleton>} imported policy object\n */\nexport async function importPolicy({\n policyId,\n importData,\n options = { deps: true, prereqs: false },\n state,\n}: {\n policyId: string;\n importData: PolicyExportInterface;\n options?: PolicyImportOptions;\n state: State;\n}): Promise<PolicySkeleton> {\n let response = null;\n const errors = [];\n const imported = [];\n for (const id of Object.keys(importData.policy)) {\n if (id === policyId) {\n try {\n const policyData = importData.policy[id];\n delete policyData._rev;\n if (options.policySetName) {\n policyData.applicationName = options.policySetName;\n }\n if (options.prereqs) {\n try {\n await importPolicyPrerequisites({\n policyData,\n exportData: importData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n try {\n response = await putPolicy({\n policyId: policyData._id,\n policyData,\n state,\n });\n imported.push(id);\n } catch (error) {\n errors.push(error);\n }\n if (options.deps) {\n try {\n await importPolicyDependencies({\n policyData,\n exportData: importData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n } catch (error) {\n errors.push(error);\n }\n }\n }\n if (errors.length) {\n const errorMessages = errors\n .map((error) => error.response?.data?.message || error.message)\n .join('\\n');\n throw new Error(`Import error:\\n${errorMessages}`);\n }\n if (0 === imported.length) {\n throw new Error(`Import error:\\n${policyId} not found in import data!`);\n }\n return response;\n}\n\n/**\n * Import first policy\n * @param {PolicyExportInterface} importData import data\n * @param {PolicyImportOptions} options import options\n * @returns {Promise<PolicySkeleton>} imported policy object\n */\nexport async function importFirstPolicy({\n importData,\n options = { deps: true, prereqs: false },\n state,\n}: {\n importData: PolicyExportInterface;\n options?: PolicyImportOptions;\n state: State;\n}): Promise<PolicySkeleton> {\n let response = null;\n const errors = [];\n const imported = [];\n for (const id of Object.keys(importData.policy)) {\n try {\n const policyData = importData.policy[id];\n delete policyData._rev;\n if (options.policySetName) {\n policyData.applicationName = options.policySetName;\n }\n if (options.prereqs) {\n try {\n await importPolicyPrerequisites({\n policyData,\n exportData: importData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n try {\n response = await putPolicy({\n policyId: policyData._id,\n policyData,\n state,\n });\n imported.push(id);\n } catch (error) {\n errors.push(error);\n }\n if (options.deps) {\n try {\n await importPolicyDependencies({\n policyData,\n exportData: importData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n } catch (error) {\n errors.push(error);\n }\n break;\n }\n if (errors.length) {\n const errorMessages = errors\n .map((error) => error.response?.data?.message || error.message)\n .join('\\n');\n throw new Error(`Import error:\\n${errorMessages}`);\n }\n if (0 === imported.length) {\n throw new Error(`Import error:\\nNo policy found in import data!`);\n }\n return response;\n}\n\n/**\n * Import policies\n * @param {PolicyExportInterface} importData import data\n * @param {PolicyImportOptions} options import options\n * @returns {Promise<PolicySkeleton[]>} array of imported policy objects\n */\nexport async function importPolicies({\n importData,\n options = { deps: true, prereqs: false },\n state,\n}: {\n importData: PolicyExportInterface;\n options?: PolicyImportOptions;\n state: State;\n}): Promise<PolicySkeleton[]> {\n const response = [];\n const errors = [];\n const imported = [];\n for (const id of Object.keys(importData.policy)) {\n try {\n const policyData = importData.policy[id];\n delete policyData._rev;\n if (options.policySetName) {\n policyData.applicationName = options.policySetName;\n }\n if (options.prereqs) {\n try {\n await importPolicyPrerequisites({\n policyData,\n exportData: importData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n try {\n response.push(\n await putPolicy({ policyId: policyData._id, policyData, state })\n );\n imported.push(id);\n } catch (error) {\n errors.push(error);\n }\n if (options.deps) {\n try {\n await importPolicyDependencies({\n policyData,\n exportData: importData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length) {\n const errorMessages = errors\n .map((error) => error.response?.data?.message || error.message)\n .join('\\n');\n throw new Error(`Import error:\\n${errorMessages}`);\n }\n if (0 === imported.length) {\n throw new Error(`Import error:\\nNo policies found in import data!`);\n }\n return response;\n}\n"]}
1
+ {"version":3,"sources":["../src/ops/PolicyOps.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,SAAS,EACT,SAAS,EACT,YAAY,EACb,MAAM,oBAAoB,CAAC;AAG5B,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,EACL,eAAe,EACf,iBAAiB,EACjB,cAAc,EACd,oBAAoB,EACpB,cAAc,EACf,MAAM,iBAAiB,CAAC;AAMzB,OAAO,K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,GACN,EAAE;IACD,UAAU,EAAE,qBAAqB,CAAC;IAClC,OAAO,CAAC,EAAE,mBAAmB,CAAC;IAC9B,KAAK,EAAE,KAAK,CAAC;CACd,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC,CAuD5B","file":"PolicyOps.d.ts","sourcesContent":["import {\n getPolicies as _getPolicies,\n getPoliciesByPolicySet as _getPoliciesByPolicySet,\n getPolicy,\n putPolicy,\n deletePolicy,\n} from '../api/PoliciesApi';\nimport { getScript, putScript } from './ScriptOps';\nimport { convertBase64TextToArray } from './utils/ExportImportUtils';\nimport { ExportMetaData } from './OpsTypes';\nimport {\n PolicyCondition,\n PolicySetSkeleton,\n PolicySkeleton,\n ResourceTypeSkeleton,\n ScriptSkeleton,\n} from '../api/ApiTypes';\nimport { getMetadata } from './utils/ExportImportUtils';\nimport { debugMessage } from './utils/Console';\nimport { getResourceType } from '../api/ResourceTypesApi';\nimport { createPolicySet, getPolicySet, updatePolicySet } from './PolicySetOps';\nimport { createResourceType, updateResourceType } from './ResourceTypeOps';\nimport State from '../shared/State';\n\nexport default class PolicyOps {\n state: State;\n constructor(state: State) {\n this.state = state;\n }\n\n /**\n * Get all policies\n * @returns {Promise<PolicySkeleton>} a promise that resolves to an array of policy set objects\n */\n async getPolicies(): Promise<PolicySkeleton[]> {\n return getPolicies({ state: this.state });\n }\n\n /**\n * Get policies by policy set\n * @param {string} policySetId policy set id/name\n * @returns {Promise<PolicySkeleton[]>} a promise resolving to an array of policy objects\n */\n async getPoliciesByPolicySet(policySetId: string): Promise<PolicySkeleton[]> {\n return getPoliciesByPolicySet({ policySetId, state: this.state });\n }\n\n async getPolicy(policyId: string) {\n return getPolicy({ policyId, state: this.state });\n }\n\n async putPolicy(policyId: string, policyData: PolicySkeleton) {\n return putPolicy({ policyId, policyData, state: this.state });\n }\n\n async deletePolicy(policyId: string) {\n return deletePolicy({ policyId, state: this.state });\n }\n\n /**\n * Export policy\n * @param {string} policyId policy id/name\n * @returns {Promise<PolicyExportInterface>} a promise that resolves to a PolicyExportInterface object\n */\n async exportPolicy(\n policyId: string,\n options: PolicyExportOptions = {\n deps: true,\n prereqs: false,\n useStringArrays: true,\n }\n ): Promise<PolicyExportInterface> {\n return exportPolicy({ policyId, options, state: this.state });\n }\n\n /**\n * Export policies\n * @param {PolicyExportOptions} options export options\n * @returns {Promise<PolicyExportInterface>} a promise that resolves to an PolicyExportInterface object\n */\n async exportPolicies(\n options: PolicyExportOptions = {\n deps: true,\n prereqs: false,\n useStringArrays: true,\n }\n ): Promise<PolicyExportInterface> {\n return exportPolicies({ options, state: this.state });\n }\n\n /**\n * Export policies by policy set\n * @param {string} policySetName policy set id/name\n * @param {PolicyExportOptions} options export options\n * @returns {Promise<PolicyExportInterface>} a promise that resolves to an PolicyExportInterface object\n */\n async exportPoliciesByPolicySet(\n policySetName: string,\n options: PolicyExportOptions = {\n deps: true,\n prereqs: false,\n useStringArrays: true,\n }\n ): Promise<PolicyExportInterface> {\n return exportPoliciesByPolicySet({\n policySetName,\n options,\n state: this.state,\n });\n }\n\n /**\n * Import policy by id\n * @param {string} policyId policy id\n * @param {PolicyExportInterface} importData import data\n * @param {PolicyImportOptions} options import options\n * @returns {Promise<PolicySkeleton>} imported policy object\n */\n async importPolicy(\n policyId: string,\n importData: PolicyExportInterface,\n options: PolicyImportOptions = { deps: true, prereqs: false }\n ): Promise<PolicySkeleton> {\n return importPolicy({ policyId, importData, options, state: this.state });\n }\n\n /**\n * Import first policy\n * @param {PolicyExportInterface} importData import data\n * @param {PolicyImportOptions} options import options\n * @returns {Promise<PolicySkeleton>} imported policy object\n */\n async importFirstPolicy(\n importData: PolicyExportInterface,\n options: PolicyImportOptions = { deps: true, prereqs: false }\n ): Promise<PolicySkeleton> {\n return importFirstPolicy({ importData, options, state: this.state });\n }\n\n /**\n * Import policies\n * @param {PolicyExportInterface} importData import data\n * @param {PolicyImportOptions} options import options\n * @returns {Promise<PolicySkeleton[]>} array of imported policy objects\n */\n async importPolicies(\n importData: PolicyExportInterface,\n options: PolicyImportOptions = { deps: true, prereqs: false }\n ): Promise<PolicySkeleton[]> {\n return importPolicies({ importData, options, state: this.state });\n }\n}\n\nexport interface PolicyExportInterface {\n meta?: ExportMetaData;\n script: Record<string, ScriptSkeleton>;\n resourcetype: Record<string, ResourceTypeSkeleton>;\n policy: Record<string, PolicySkeleton>;\n policyset: Record<string, PolicySetSkeleton>;\n}\n\n/**\n * Policy export options\n */\nexport interface PolicyExportOptions {\n /**\n * Include any dependencies (scripts).\n */\n deps: boolean;\n /**\n * Include any prerequisites (policy sets, resource types).\n */\n prereqs: boolean;\n /**\n * Use string arrays to store multi-line text in scripts.\n */\n useStringArrays: boolean;\n}\n\n/**\n * Policy import options\n */\nexport interface PolicyImportOptions {\n /**\n * Include any dependencies (scripts).\n */\n deps: boolean;\n /**\n * Include any prerequisites (policy sets, resource types).\n */\n prereqs: boolean;\n /**\n * Import policies into different policy set\n */\n policySetName?: string;\n}\n\n/**\n * Create an empty export template\n * @returns {PolicyExportInterface} an empty export template\n */\nfunction createPolicyExportTemplate({\n state,\n}: {\n state: State;\n}): PolicyExportInterface {\n return {\n meta: getMetadata({ state }),\n script: {},\n policy: {},\n resourcetype: {},\n policyset: {},\n } as PolicyExportInterface;\n}\n\n/**\n * Get all policies\n * @returns {Promise<PolicySkeleton>} a promise that resolves to an array of policy set objects\n */\nexport async function getPolicies({\n state,\n}: {\n state: State;\n}): Promise<PolicySkeleton[]> {\n const { result } = await _getPolicies({ state });\n return result;\n}\n\n/**\n * Get policies by policy set\n * @param {string} policySetId policy set id/name\n * @returns {Promise<PolicySkeleton[]>} a promise resolving to an array of policy objects\n */\nexport async function getPoliciesByPolicySet({\n policySetId,\n state,\n}: {\n policySetId: string;\n state: State;\n}): Promise<PolicySkeleton[]> {\n const data = await _getPoliciesByPolicySet({ policySetId, state });\n return data.result;\n}\n\nexport { getPolicy, putPolicy, deletePolicy };\n\n/**\n * Find all script references in a deeply-nested policy condition object\n * @param {PolicyCondition} condition condition object\n * @returns {string[]} array of script UUIDs\n * \n * Sample condition block:\n * \n \"condition\": {\n \"type\": \"AND\",\n \"conditions\": [\n {\n \"type\": \"Script\",\n \"scriptId\": \"62f18ede-e5e7-4a7b-8b73-1b02fcbd241a\"\n },\n {\n \"type\": \"AuthenticateToService\",\n \"authenticateToService\": \"TxAuthz\"\n },\n {\n \"type\": \"OR\",\n \"conditions\": [\n {\n \"type\": \"Session\",\n \"maxSessionTime\": 5,\n \"terminateSession\": false\n },\n {\n \"type\": \"OAuth2Scope\",\n \"requiredScopes\": [\n \"openid\"\n ]\n },\n {\n \"type\": \"NOT\",\n \"condition\": {\n \"type\": \"Script\",\n \"scriptId\": \"729ee140-a4e9-43af-b358-d60eeda13cc3\"\n }\n }\n ]\n }\n ]\n },\n*/\nexport function findScriptUuids(condition: PolicyCondition): string[] {\n let scriptUuids: string[] = [];\n if (!condition) return scriptUuids;\n if (\n condition.type === 'AND' ||\n condition.type === 'OR' ||\n condition.type === 'NOT'\n ) {\n // single condition\n if (condition.condition) {\n scriptUuids.push(...findScriptUuids(condition.condition));\n }\n // array of conditions\n if (condition.conditions) {\n for (const cond of condition.conditions) {\n scriptUuids.push(...findScriptUuids(cond));\n }\n }\n } else if (condition.type === 'Script') {\n scriptUuids.push(condition.scriptId as string);\n }\n // de-duplicate\n scriptUuids = [...new Set(scriptUuids)];\n return scriptUuids;\n}\n\n/**\n * Get scripts for a policy object\n * @param {PolicySkeleton} policyData policy object\n * @returns {Promise<ScriptSkeleton[]>} a promise that resolves to an array of script objects\n */\nexport async function getScripts({\n policyData,\n state,\n}: {\n policyData: PolicySkeleton;\n state: State;\n}): Promise<ScriptSkeleton[]> {\n debugMessage({\n message: `PolicyOps.getScripts: start [policy=${policyData['name']}]`,\n state,\n });\n const errors = [];\n const scripts = [];\n try {\n const scriptUuids = findScriptUuids(policyData.condition);\n debugMessage({ message: `found scripts: ${scriptUuids}`, state });\n for (const scriptUuid of scriptUuids) {\n try {\n const script = await getScript({ scriptId: scriptUuid, state });\n scripts.push(script);\n } catch (error) {\n error.message = `Error retrieving script ${scriptUuid} referenced in policy ${policyData['name']}: ${error.message}`;\n errors.push(error);\n }\n }\n } catch (error) {\n error.message = `Error finding scripts in policy ${policyData['name']}: ${error.message}`;\n errors.push(error);\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Export error:\\n${errorMessages}`);\n }\n debugMessage({ message: `PolicySetOps.getScripts: end`, state });\n return scripts;\n}\n\n/**\n * Helper function to export dependencies of a policy set\n * @param {PolicySkeleton} policyData policy set data\n * @param {PolicyExportInterface} exportData export data\n */\nasync function exportPolicyPrerequisites({\n policyData,\n exportData,\n state,\n}: {\n policyData: PolicySkeleton;\n exportData: PolicyExportInterface;\n state: State;\n}) {\n debugMessage({\n message: `PolicyOps.exportPolicyPrerequisites: start [policy=${policyData['name']}]`,\n state,\n });\n // resource types\n if (policyData.resourceTypeUuid) {\n const resourceType = await getResourceType({\n resourceTypeUuid: policyData.resourceTypeUuid,\n state,\n });\n exportData.resourcetype[policyData.resourceTypeUuid] = resourceType;\n }\n // policy set\n if (policyData.applicationName) {\n const policySet = await getPolicySet({\n policySetName: policyData.applicationName,\n state,\n });\n exportData.policyset[policyData.applicationName] = policySet;\n }\n debugMessage({\n message: `PolicySetOps.exportPolicyPrerequisites: end`,\n state,\n });\n}\n\n/**\n * Helper function to export dependencies of a policy set\n * @param {unknown} policyData policy set data\n * @param {PolicyExportOptions} options export options\n * @param {PolicyExportInterface} exportData export data\n */\nasync function exportPolicyDependencies({\n policyData,\n options,\n exportData,\n state,\n}: {\n policyData: PolicySkeleton;\n options: PolicyExportOptions;\n exportData: PolicyExportInterface;\n state: State;\n}) {\n debugMessage({\n message: `PolicyOps.exportPolicyDependencies: start [policy=${policyData['name']}]`,\n state,\n });\n // scripts\n const scripts = await getScripts({ policyData, state });\n for (const scriptData of scripts) {\n if (options.useStringArrays) {\n scriptData.script = convertBase64TextToArray(scriptData.script as string);\n }\n exportData.script[scriptData._id] = scriptData;\n }\n debugMessage({\n message: `PolicySetOps.exportPolicySetDependencies: end`,\n state,\n });\n}\n\n/**\n * Export policy\n * @param {string} policyId policy id/name\n * @returns {Promise<PolicyExportInterface>} a promise that resolves to a PolicyExportInterface object\n */\nexport async function exportPolicy({\n policyId,\n options = {\n deps: true,\n prereqs: false,\n useStringArrays: true,\n },\n state,\n}: {\n policyId: string;\n options?: PolicyExportOptions;\n state: State;\n}): Promise<PolicyExportInterface> {\n debugMessage({ message: `PolicyOps.exportPolicy: start`, state });\n const policyData = await getPolicy({ policyId, state });\n const exportData = createPolicyExportTemplate({ state });\n exportData.policy[policyData._id] = policyData;\n if (options.prereqs) {\n await exportPolicyPrerequisites({ policyData, exportData, state });\n }\n if (options.deps) {\n await exportPolicyDependencies({ policyData, options, exportData, state });\n }\n debugMessage({ message: `PolicyOps.exportPolicy: end`, state });\n return exportData;\n}\n\n/**\n * Export policies\n * @param {PolicyExportOptions} options export options\n * @returns {Promise<PolicyExportInterface>} a promise that resolves to an PolicyExportInterface object\n */\nexport async function exportPolicies({\n options = {\n deps: true,\n prereqs: false,\n useStringArrays: true,\n },\n state,\n}: {\n options?: PolicyExportOptions;\n state: State;\n}): Promise<PolicyExportInterface> {\n debugMessage({ message: `PolicyOps.exportPolicies: start`, state });\n const exportData = createPolicyExportTemplate({ state });\n const errors = [];\n try {\n const policies = await getPolicies({ state });\n for (const policyData of policies) {\n exportData.policy[policyData._id] = policyData;\n if (options.prereqs) {\n try {\n await exportPolicyPrerequisites({ policyData, exportData, state });\n } catch (error) {\n errors.push(error);\n }\n }\n if (options.deps) {\n try {\n await exportPolicyDependencies({\n policyData,\n options,\n exportData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n }\n } catch (error) {\n errors.push(error);\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Export error:\\n${errorMessages}`);\n }\n debugMessage({ message: `PolicyOps.exportPolicies: end`, state });\n return exportData;\n}\n\n/**\n * Export policies by policy set\n * @param {string} policySetName policy set id/name\n * @param {PolicyExportOptions} options export options\n * @returns {Promise<PolicyExportInterface>} a promise that resolves to an PolicyExportInterface object\n */\nexport async function exportPoliciesByPolicySet({\n policySetName,\n options = {\n deps: true,\n prereqs: false,\n useStringArrays: true,\n },\n state,\n}: {\n policySetName: string;\n options?: PolicyExportOptions;\n state: State;\n}): Promise<PolicyExportInterface> {\n debugMessage({ message: `PolicyOps.exportPolicies: start`, state });\n const exportData = createPolicyExportTemplate({ state });\n const errors = [];\n try {\n const policies = await getPoliciesByPolicySet({\n policySetId: policySetName,\n state,\n });\n for (const policyData of policies) {\n exportData.policy[policyData._id] = policyData;\n if (options.prereqs) {\n try {\n await exportPolicyPrerequisites({ policyData, exportData, state });\n } catch (error) {\n errors.push(error);\n }\n }\n if (options.deps) {\n try {\n await exportPolicyDependencies({\n policyData,\n options,\n exportData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n }\n } catch (error) {\n errors.push(error);\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Export error:\\n${errorMessages}`);\n }\n debugMessage({ message: `PolicyOps.exportPolicies: end`, state });\n return exportData;\n}\n\n/**\n * Helper function to import hard dependencies of a policy\n * @param {PolicySkeleton} policyData policy object\n * @param {PolicyExportInterface} exportData export data\n */\nasync function importPolicyPrerequisites({\n policyData,\n exportData,\n state,\n}: {\n policyData: PolicySkeleton;\n exportData: PolicyExportInterface;\n state: State;\n}) {\n debugMessage({\n message: `PolicyOps.importPolicyHardDependencies: start [policy=${policyData._id}]`,\n state,\n });\n const errors = [];\n try {\n // resource type\n if (exportData.resourcetype[policyData.resourceTypeUuid]) {\n try {\n debugMessage({\n message: `Importing resource type ${policyData.resourceTypeUuid}`,\n state,\n });\n await createResourceType({\n resourceTypeData:\n exportData.resourcetype[policyData.resourceTypeUuid],\n state,\n });\n } catch (error) {\n if (error.response?.status === 409)\n await updateResourceType({\n resourceTypeUuid: policyData.resourceTypeUuid,\n resourceTypeData:\n exportData.resourcetype[policyData.resourceTypeUuid],\n state,\n });\n else throw error;\n }\n }\n // policy set\n if (exportData.policyset[policyData.applicationName]) {\n try {\n debugMessage({\n message: `Importing policy set ${policyData.applicationName}`,\n state,\n });\n await createPolicySet({\n policySetData: exportData.policyset[policyData.applicationName],\n state,\n });\n } catch (error) {\n if (error.response?.status === 409)\n await updatePolicySet({\n policySetData: exportData.policyset[policyData.applicationName],\n state,\n });\n else throw error;\n }\n }\n } catch (error) {\n error.message = `Error importing hard dependencies for policy ${\n policyData._id\n }: ${error.response?.data?.message || error.message}`;\n errors.push(error);\n }\n if (errors.length) {\n const errorMessages = errors\n .map((error) => error.response?.data?.message || error.message)\n .join('\\n');\n throw new Error(`Import hard dependencies error:\\n${errorMessages}`);\n }\n debugMessage({\n message: `PolicyOps.importPolicyHardDependencies: end`,\n state,\n });\n}\n\n/**\n * Helper function to import soft dependencies of a policy\n * @param {PolicySkeleton} policyData policy object\n * @param {PolicyExportInterface} exportData export data\n */\nasync function importPolicyDependencies({\n policyData,\n exportData,\n state,\n}: {\n policyData: PolicySkeleton;\n exportData: PolicyExportInterface;\n state: State;\n}) {\n debugMessage({\n message: `PolicyOps.importPolicySoftDependencies: start [policy=${policyData._id}]`,\n state,\n });\n const errors = [];\n try {\n // scripts\n const scriptUuids = findScriptUuids(policyData.condition);\n for (const scriptUuid of scriptUuids) {\n try {\n const scriptData = exportData.script[scriptUuid];\n debugMessage({ message: `Importing script ${scriptUuid}`, state });\n await putScript({ scriptId: scriptUuid, scriptData, state });\n } catch (error) {\n debugMessage({ message: error.response?.data, state });\n error.message = `Error importing script ${scriptUuid} for policy ${\n policyData._id\n }: ${error.response?.data?.message || error.message}`;\n errors.push(error);\n }\n }\n } catch (error) {\n error.message = `Error importing soft dependencies for policy ${\n policyData._id\n }: ${error.response?.data?.message || error.message}`;\n errors.push(error);\n }\n if (errors.length) {\n const errorMessages = errors\n .map((error) => error.response?.data?.message || error.message)\n .join('\\n');\n throw new Error(`Import soft dependencies error:\\n${errorMessages}`);\n }\n debugMessage({\n message: `PolicyOps.importPolicySoftDependencies: end`,\n state,\n });\n}\n\n/**\n * Import policy by id\n * @param {string} policyId policy id\n * @param {PolicyExportInterface} importData import data\n * @param {PolicyImportOptions} options import options\n * @returns {Promise<PolicySkeleton>} imported policy object\n */\nexport async function importPolicy({\n policyId,\n importData,\n options = { deps: true, prereqs: false },\n state,\n}: {\n policyId: string;\n importData: PolicyExportInterface;\n options?: PolicyImportOptions;\n state: State;\n}): Promise<PolicySkeleton> {\n let response = null;\n const errors = [];\n const imported = [];\n for (const id of Object.keys(importData.policy)) {\n if (id === policyId) {\n try {\n const policyData = importData.policy[id];\n delete policyData._rev;\n if (options.policySetName) {\n policyData.applicationName = options.policySetName;\n }\n if (options.prereqs) {\n try {\n await importPolicyPrerequisites({\n policyData,\n exportData: importData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n try {\n response = await putPolicy({\n policyId: policyData._id,\n policyData,\n state,\n });\n imported.push(id);\n } catch (error) {\n errors.push(error);\n }\n if (options.deps) {\n try {\n await importPolicyDependencies({\n policyData,\n exportData: importData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n } catch (error) {\n errors.push(error);\n }\n }\n }\n if (errors.length) {\n const errorMessages = errors\n .map((error) => error.response?.data?.message || error.message)\n .join('\\n');\n throw new Error(`Import error:\\n${errorMessages}`);\n }\n if (0 === imported.length) {\n throw new Error(`Import error:\\n${policyId} not found in import data!`);\n }\n return response;\n}\n\n/**\n * Import first policy\n * @param {PolicyExportInterface} importData import data\n * @param {PolicyImportOptions} options import options\n * @returns {Promise<PolicySkeleton>} imported policy object\n */\nexport async function importFirstPolicy({\n importData,\n options = { deps: true, prereqs: false },\n state,\n}: {\n importData: PolicyExportInterface;\n options?: PolicyImportOptions;\n state: State;\n}): Promise<PolicySkeleton> {\n let response = null;\n const errors = [];\n const imported = [];\n for (const id of Object.keys(importData.policy)) {\n try {\n const policyData = importData.policy[id];\n delete policyData._rev;\n if (options.policySetName) {\n policyData.applicationName = options.policySetName;\n }\n if (options.prereqs) {\n try {\n await importPolicyPrerequisites({\n policyData,\n exportData: importData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n try {\n response = await putPolicy({\n policyId: policyData._id,\n policyData,\n state,\n });\n imported.push(id);\n } catch (error) {\n errors.push(error);\n }\n if (options.deps) {\n try {\n await importPolicyDependencies({\n policyData,\n exportData: importData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n } catch (error) {\n errors.push(error);\n }\n break;\n }\n if (errors.length) {\n const errorMessages = errors\n .map((error) => error.response?.data?.message || error.message)\n .join('\\n');\n throw new Error(`Import error:\\n${errorMessages}`);\n }\n if (0 === imported.length) {\n throw new Error(`Import error:\\nNo policy found in import data!`);\n }\n return response;\n}\n\n/**\n * Import policies\n * @param {PolicyExportInterface} importData import data\n * @param {PolicyImportOptions} options import options\n * @returns {Promise<PolicySkeleton[]>} array of imported policy objects\n */\nexport async function importPolicies({\n importData,\n options = { deps: true, prereqs: false },\n state,\n}: {\n importData: PolicyExportInterface;\n options?: PolicyImportOptions;\n state: State;\n}): Promise<PolicySkeleton[]> {\n const response = [];\n const errors = [];\n const imported = [];\n for (const id of Object.keys(importData.policy)) {\n try {\n const policyData = importData.policy[id];\n delete policyData._rev;\n if (options.policySetName) {\n policyData.applicationName = options.policySetName;\n }\n if (options.prereqs) {\n try {\n await importPolicyPrerequisites({\n policyData,\n exportData: importData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n try {\n response.push(\n await putPolicy({ policyId: policyData._id, policyData, state })\n );\n imported.push(id);\n } catch (error) {\n errors.push(error);\n }\n if (options.deps) {\n try {\n await importPolicyDependencies({\n policyData,\n exportData: importData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length) {\n const errorMessages = errors\n .map((error) => error.response?.data?.message || error.message)\n .join('\\n');\n throw new Error(`Import error:\\n${errorMessages}`);\n }\n if (0 === imported.length) {\n throw new Error(`Import error:\\nNo policies found in import data!`);\n }\n return response;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ops/PolicySetOps.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EAEf,YAAY,EACZ,eAAe,EACf,eAAe,EAChB,MAAM,qBAAqB,CAAC;AAG7B,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,EACL,iBAAiB,EACjB,cAAc,EACd,oBAAoB,EACpB,cAAc,EACf,MAAM,iBAAiB,CAAC;AAUzB,OAAO,KAAK,MAAM,iBAAiB,CAAC;AAEpC,MAAM,CAAC,OAAO,OAAO,YAAY;IAC/B,KAAK,EAAE,KAAK,CAAC;gBACD,KAAK,EAAE,KAAK;IAIxB;;;OAGG;IACG,aAAa,IAAI,OAAO,CAAC,iBAAiB,EAAE,CAAC;IAI7C,YAAY,CAAC,aAAa,EAAE,MAAM;IAIlC,eAAe,CAAC,aAAa,EAAE,iBAAiB;IAIhD,eAAe,CAAC,aAAa,EAAE,iBAAiB;IAIhD,eAAe,CAAC,aAAa,EAAE,MAAM;IAI3C;;;;;OAKG;IACG,eAAe,CACnB,aAAa,EAAE,MAAM,EACrB,OAAO,GAAE,sBAIR,GACA,OAAO,CAAC,wBAAwB,CAAC;IAIpC;;;;OAIG;IACG,gBAAgB,CACpB,OAAO,GAAE,sBAIR,GACA,OAAO,CAAC,wBAAwB,CAAC;IAIpC;;;;;OAKG;IACG,eAAe,CACnB,aAAa,EAAE,MAAM,EACrB,UAAU,EAAE,wBAAwB,EACpC,OAAO,GAAE,sBAAuD;IAUlE;;;;OAIG;IACG,oBAAoB,CACxB,UAAU,EAAE,wBAAwB,EACpC,OAAO,GAAE,sBAAuD;IAKlE;;;;OAIG;IACG,gBAAgB,CACpB,UAAU,EAAE,wBAAwB,EACpC,OAAO,GAAE,sBAAuD;CAInE;AAED,MAAM,WAAW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;;;GAKG;AACH,wBAAsB,eAAe,CAAC,EACpC,aAAa,EACb,UAAU,EACV,OAAwC,EACxC,KAAK,GACN,EAAE;IACD,aAAa,EAAE,MAAM,CAAC;IACtB,UAAU,EAAE,wBAAwB,CAAC;IACrC,OAAO,CAAC,EAAE,sBAAsB,CAAC;IACjC,KAAK,EAAE,KAAK,CAAC;CACd,gBAuDA;AAED;;;;GAIG;AACH,wBAAsB,oBAAoB,CAAC,EACzC,UAAU,EACV,OAAwC,EACxC,KAAK,GACN,EAAE;IACD,UAAU,EAAE,wBAAwB,CAAC;IACrC,OAAO,CAAC,EAAE,sBAAsB,CAAC;IACjC,KAAK,EAAE,KAAK,CAAC;CACd,gBAqDA;AAED;;;;GAIG;AACH,wBAAsB,gBAAgB,CAAC,EACrC,UAAU,EACV,OAAwC,EACxC,KAAK,GACN,EAAE;IACD,UAAU,EAAE,wBAAwB,CAAC;IACrC,OAAO,CAAC,EAAE,sBAAsB,CAAC;IACjC,KAAK,EAAE,KAAK,CAAC;CACd,gBAmDA","file":"PolicySetOps.d.ts","sourcesContent":["import {\n deletePolicySet,\n getPolicySets as _getPolicySets,\n getPolicySet,\n createPolicySet,\n updatePolicySet,\n} from '../api/PolicySetApi';\nimport { putScript } from './ScriptOps';\nimport { convertBase64TextToArray } from './utils/ExportImportUtils';\nimport { ExportMetaData } from './OpsTypes';\nimport {\n PolicySetSkeleton,\n PolicySkeleton,\n ResourceTypeSkeleton,\n ScriptSkeleton,\n} from '../api/ApiTypes';\nimport { getMetadata } from './utils/ExportImportUtils';\nimport { debugMessage } from './utils/Console';\nimport { getResourceType, putResourceType } from '../api/ResourceTypesApi';\nimport {\n findScriptUuids,\n getPoliciesByPolicySet,\n getScripts,\n putPolicy,\n} from './PolicyOps';\nimport State from '../shared/State';\n\nexport default class PolicySetOps {\n state: State;\n constructor(state: State) {\n this.state = state;\n }\n\n /**\n * Get all policy sets\n * @returns {Promise} a promise that resolves to an array of policy set objects\n */\n async getPolicySets(): Promise<PolicySetSkeleton[]> {\n return getPolicySets({ state: this.state });\n }\n\n async getPolicySet(policySetName: string) {\n return getPolicySet({ policySetName, state: this.state });\n }\n\n async createPolicySet(policySetData: PolicySetSkeleton) {\n return createPolicySet({ policySetData, state: this.state });\n }\n\n async updatePolicySet(policySetData: PolicySetSkeleton) {\n return updatePolicySet({ policySetData, state: this.state });\n }\n\n async deletePolicySet(policySetName: string) {\n return deletePolicySet({ policySetName, state: this.state });\n }\n\n /**\n * Export policy set\n * @param {string} policySetName policy set name\n * @param {PolicySetExportOptions} options export options\n * @returns {Promise<PolicySetExportInterface>} a promise that resolves to an PolicySetExportInterface object\n */\n async exportPolicySet(\n policySetName: string,\n options: PolicySetExportOptions = {\n deps: true,\n prereqs: false,\n useStringArrays: true,\n }\n ): Promise<PolicySetExportInterface> {\n return exportPolicySet({ policySetName, options, state: this.state });\n }\n\n /**\n * Export policy sets\n * @param {PolicySetExportOptions} options export options\n * @returns {Promise<PolicySetExportInterface>} a promise that resolves to an PolicySetExportInterface object\n */\n async exportPolicySets(\n options: PolicySetExportOptions = {\n deps: true,\n prereqs: false,\n useStringArrays: true,\n }\n ): Promise<PolicySetExportInterface> {\n return exportPolicySets({ options, state: this.state });\n }\n\n /**\n * Import policy set\n * @param {string} policySetName policy set name\n * @param {PolicySetExportInterface} importData import data\n * @param {PolicySetImportOptions} options import options\n */\n async importPolicySet(\n policySetName: string,\n importData: PolicySetExportInterface,\n options: PolicySetImportOptions = { deps: true, prereqs: false }\n ) {\n return importPolicySet({\n policySetName,\n importData,\n options,\n state: this.state,\n });\n }\n\n /**\n * Import first policy set\n * @param {PolicySetExportInterface} importData import data\n * @param {PolicySetImportOptions} options import options\n */\n async importFirstPolicySet(\n importData: PolicySetExportInterface,\n options: PolicySetImportOptions = { deps: true, prereqs: false }\n ) {\n return importFirstPolicySet({ importData, options, state: this.state });\n }\n\n /**\n * Import policy sets\n * @param {PolicySetExportInterface} importData import data\n * @param {PolicySetImportOptions} options import options\n */\n async importPolicySets(\n importData: PolicySetExportInterface,\n options: PolicySetImportOptions = { deps: true, prereqs: false }\n ) {\n return importPolicySets({ importData, options, state: this.state });\n }\n}\n\nexport interface PolicySetExportInterface {\n meta?: ExportMetaData;\n script: Record<string, ScriptSkeleton>;\n resourcetype: Record<string, ResourceTypeSkeleton>;\n policy: Record<string, PolicySkeleton>;\n policyset: Record<string, PolicySetSkeleton>;\n}\n\n/**\n * Application/policy set export options\n */\nexport interface PolicySetExportOptions {\n /**\n * Include any dependencies (policies, scripts, resource types).\n */\n deps: boolean;\n /**\n * Include any prerequisites (policy sets, resource types).\n */\n prereqs: boolean;\n /**\n * Use string arrays to store multi-line text in scripts.\n */\n useStringArrays: boolean;\n}\n\n/**\n * Policy set import options\n */\nexport interface PolicySetImportOptions {\n /**\n * Include any dependencies (policies, scripts, resource types).\n */\n deps: boolean;\n /**\n * Include any prerequisites (policy sets, resource types).\n */\n prereqs: boolean;\n}\n\n/**\n * Create an empty export template\n * @returns {PolicySetExportInterface} an empty export template\n */\nfunction createPolicySetExportTemplate({\n state,\n}: {\n state: State;\n}): PolicySetExportInterface {\n return {\n meta: getMetadata({ state }),\n script: {},\n policy: {},\n resourcetype: {},\n policyset: {},\n } as PolicySetExportInterface;\n}\n\n/**\n * Get all policy sets\n * @returns {Promise} a promise that resolves to an array of policy set objects\n */\nexport async function getPolicySets({\n state,\n}: {\n state: State;\n}): Promise<PolicySetSkeleton[]> {\n const { result } = await _getPolicySets({ state });\n return result;\n}\n\nexport { getPolicySet, createPolicySet, updatePolicySet, deletePolicySet };\n\n/**\n * Helper function to export prerequisites of a policy set\n * @param {PolicySetSkeleton} policySetData policy set object\n * @param {PolicySetExportInterface} exportData export data\n */\nasync function exportPolicySetPrerequisites({\n policySetData,\n exportData,\n state,\n}: {\n policySetData: PolicySetSkeleton;\n exportData: PolicySetExportInterface;\n state: State;\n}) {\n debugMessage(\n `PolicySetOps.exportPolicySetPrerequisites: start [policySet=${policySetData['name']}]`\n );\n const errors = [];\n // resource types\n for (const resourceTypeUuid of policySetData.resourceTypeUuids) {\n try {\n const resourceType = await getResourceType({ resourceTypeUuid, state });\n exportData.resourcetype[resourceTypeUuid] = resourceType;\n } catch (error) {\n error.message = `Error retrieving resource type ${resourceTypeUuid} for policy set ${policySetData.name}: ${error.message}`;\n errors.push(error);\n }\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Export dependencies error:\\n${errorMessages}`);\n }\n debugMessage(`PolicySetOps.exportPolicySetPrerequisites: end`);\n}\n\n/**\n * Helper function to export dependencies of a policy set\n * @param {PolicySetSkeleton} policySetData policy set object\n * @param {PolicySetExportOptions} options export options\n * @param {PolicySetExportInterface} exportData export data\n */\nasync function exportPolicySetDependencies({\n policySetData,\n options,\n exportData,\n state,\n}: {\n policySetData: PolicySetSkeleton;\n options: PolicySetExportOptions;\n exportData: PolicySetExportInterface;\n state: State;\n}) {\n debugMessage(\n `PolicySetOps.exportPolicySetDependencies: start [policySet=${policySetData['name']}]`\n );\n const errors = [];\n // policies\n try {\n const policies = await getPoliciesByPolicySet({\n policySetId: policySetData.name,\n state,\n });\n for (const policy of policies) {\n exportData.policy[policy.name] = policy;\n // scripts\n try {\n const scripts = await getScripts({ policyData: policy, state });\n for (const scriptData of scripts) {\n if (options.useStringArrays) {\n scriptData.script = convertBase64TextToArray(\n scriptData.script as string\n );\n }\n exportData.script[scriptData._id] = scriptData;\n }\n } catch (error) {\n errors.push(error);\n }\n }\n } catch (error) {\n error.message = `Error retrieving policies in policy set ${policySetData.name}: ${error.message}`;\n errors.push(error);\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Export dependencies error:\\n${errorMessages}`);\n }\n debugMessage(`PolicySetOps.exportPolicySetDependencies: end`);\n}\n\n/**\n * Export policy set\n * @param {string} policySetName policy set name\n * @param {PolicySetExportOptions} options export options\n * @returns {Promise<PolicySetExportInterface>} a promise that resolves to an PolicySetExportInterface object\n */\nexport async function exportPolicySet({\n policySetName,\n options = {\n deps: true,\n prereqs: false,\n useStringArrays: true,\n },\n state,\n}: {\n policySetName: string;\n options?: PolicySetExportOptions;\n state: State;\n}): Promise<PolicySetExportInterface> {\n debugMessage(`PolicySetOps.exportPolicySet: start`);\n const exportData = createPolicySetExportTemplate({ state });\n const errors = [];\n try {\n const policySetData = await getPolicySet({ policySetName, state });\n exportData.policyset[policySetData.name] = policySetData;\n if (options.prereqs) {\n try {\n await exportPolicySetPrerequisites({\n policySetData,\n exportData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n if (options.deps) {\n try {\n await exportPolicySetDependencies({\n policySetData,\n options,\n exportData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n } catch (error) {\n errors.push(error);\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Export error:\\n${errorMessages}`);\n }\n debugMessage(`PolicySetOps.exportPolicySet: end`);\n return exportData;\n}\n\n/**\n * Export policy sets\n * @param {PolicySetExportOptions} options export options\n * @returns {Promise<PolicySetExportInterface>} a promise that resolves to an PolicySetExportInterface object\n */\nexport async function exportPolicySets({\n options = {\n deps: true,\n prereqs: false,\n useStringArrays: true,\n },\n state,\n}: {\n options: PolicySetExportOptions;\n state: State;\n}): Promise<PolicySetExportInterface> {\n debugMessage(`PolicySetOps.exportPolicySet: start`);\n const exportData = createPolicySetExportTemplate({ state });\n const errors = [];\n try {\n const policySets = await getPolicySets({ state });\n for (const policySetData of policySets) {\n exportData.policyset[policySetData.name] = policySetData;\n if (options.prereqs) {\n try {\n await exportPolicySetPrerequisites({\n policySetData,\n exportData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n if (options.deps) {\n try {\n await exportPolicySetDependencies({\n policySetData,\n options,\n exportData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n }\n } catch (error) {\n errors.push(error);\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Export error:\\n${errorMessages}`);\n }\n debugMessage(`PolicySetOps.exportPolicySet: end`);\n return exportData;\n}\n\n/**\n * Helper function to import prerequisites of a policy set (resource types)\n * @param {PolicySetSkeleton} policySetData policy set data\n * @param {PolicySetExportInterface} exportData export data\n */\nasync function importPolicySetPrerequisites({\n policySetData,\n exportData,\n state,\n}: {\n policySetData: PolicySetSkeleton;\n exportData: PolicySetExportInterface;\n state: State;\n}) {\n debugMessage(\n `PolicySetOps.importPolicySetHardDependencies: start [policySet=${policySetData['name']}]`\n );\n const errors = [];\n try {\n // resource types\n for (const resourceTypeUuid of policySetData.resourceTypeUuids) {\n if (exportData.resourcetype[resourceTypeUuid]) {\n try {\n debugMessage(`Importing resource type ${resourceTypeUuid}`);\n await putResourceType({\n resourceTypeUuid,\n resourceTypeData: exportData.resourcetype[resourceTypeUuid],\n state,\n });\n } catch (error) {\n debugMessage(error.response?.data);\n errors.push(error);\n }\n } else {\n errors.push(\n new Error(\n `No resource type definition with id ${resourceTypeUuid} found in import data.`\n )\n );\n }\n }\n } catch (error) {\n error.message = `Error importing hard dependencies for policy set ${policySetData.name}: ${error.message}`;\n errors.push(error);\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Import hard dependencies error:\\n${errorMessages}`);\n }\n debugMessage(`PolicySetOps.importPolicySetHardDependencies: end`);\n}\n\n/**\n * Helper function to import dependencies of a policy set (policies and scripts)\n * @param {PolicySetSkeleton} policySetData policy set data\n * @param {PolicySetExportInterface} exportData export data\n */\nasync function importPolicySetDependencies({\n policySetData,\n exportData,\n state,\n}: {\n policySetData: PolicySetSkeleton;\n exportData: PolicySetExportInterface;\n state: State;\n}) {\n debugMessage(\n `PolicySetOps.importPolicySetSoftDependencies: start [policySet=${policySetData['name']}]`\n );\n const errors = [];\n try {\n // policies\n try {\n const policies = Object.values(exportData.policy).filter(\n (policy) => policy.applicationName === policySetData.name\n );\n for (const policyData of policies) {\n try {\n debugMessage(`Importing policy ${policyData._id}`);\n await putPolicy({ policyId: policyData._id, policyData, state });\n } catch (error) {\n debugMessage(error.response?.data);\n error.message = `Error importing policy ${policyData._id} in policy set ${policySetData.name}: ${error.message}`;\n errors.push(error);\n }\n // scripts\n const scriptUuids = findScriptUuids(policyData.condition);\n for (const scriptUuid of scriptUuids) {\n try {\n const scriptData = exportData.script[scriptUuid];\n debugMessage(`Importing script ${scriptUuid}`);\n await putScript({ scriptId: scriptUuid, scriptData, state });\n } catch (error) {\n debugMessage(error.response?.data);\n error.message = `Error importing script ${scriptUuid} for policy ${policyData._id} in policy set ${policySetData.name}: ${error.message}`;\n errors.push(error);\n }\n }\n }\n } catch (error) {\n error.message = `Error importing policies in policy set ${policySetData.name}: ${error.message}`;\n errors.push(error);\n }\n } catch (error) {\n error.message = `Error importing soft dependencies for policy set ${policySetData.name}: ${error.message}`;\n errors.push(error);\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Import soft dependencies error:\\n${errorMessages}`);\n }\n debugMessage(`PolicySetOps.importPolicySetSoftDependencies: end`);\n}\n\n/**\n * Import policy set\n * @param {string} policySetName policy set name\n * @param {PolicySetExportInterface} importData import data\n * @param {PolicySetImportOptions} options import options\n */\nexport async function importPolicySet({\n policySetName,\n importData,\n options = { deps: true, prereqs: false },\n state,\n}: {\n policySetName: string;\n importData: PolicySetExportInterface;\n options?: PolicySetImportOptions;\n state: State;\n}) {\n let response = null;\n const errors = [];\n const imported = [];\n for (const id of Object.keys(importData.policyset)) {\n if (id === policySetName) {\n try {\n const policySetData = importData.policyset[id];\n delete policySetData._rev;\n if (options.prereqs) {\n try {\n await importPolicySetPrerequisites({\n policySetData,\n exportData: importData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n try {\n response = await createPolicySet({ policySetData, state });\n imported.push(id);\n } catch (error) {\n if (error.response?.status === 409) {\n response = await updatePolicySet({ policySetData, state });\n imported.push(id);\n } else throw error;\n }\n if (options.deps) {\n try {\n await importPolicySetDependencies({\n policySetData,\n exportData: importData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n } catch (error) {\n errors.push(error);\n }\n }\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Import error:\\n${errorMessages}`);\n }\n if (0 === imported.length) {\n throw new Error(\n `Import error:\\n${policySetName} not found in import data!`\n );\n }\n return response;\n}\n\n/**\n * Import first policy set\n * @param {PolicySetExportInterface} importData import data\n * @param {PolicySetImportOptions} options import options\n */\nexport async function importFirstPolicySet({\n importData,\n options = { deps: true, prereqs: false },\n state,\n}: {\n importData: PolicySetExportInterface;\n options?: PolicySetImportOptions;\n state: State;\n}) {\n let response = null;\n const errors = [];\n const imported = [];\n for (const id of Object.keys(importData.policyset)) {\n try {\n const policySetData = importData.policyset[id];\n delete policySetData._provider;\n delete policySetData._rev;\n if (options.prereqs) {\n try {\n await importPolicySetPrerequisites({\n policySetData,\n exportData: importData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n try {\n response = await createPolicySet({ policySetData, state });\n imported.push(id);\n } catch (error) {\n if (error.response?.status === 409) {\n response = await updatePolicySet({ policySetData, state });\n imported.push(id);\n } else throw error;\n }\n if (options.deps) {\n try {\n await importPolicySetDependencies({\n policySetData,\n exportData: importData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n } catch (error) {\n errors.push(error);\n }\n break;\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Import error:\\n${errorMessages}`);\n }\n if (0 === imported.length) {\n throw new Error(`Import error:\\nNo policy sets found in import data!`);\n }\n return response;\n}\n\n/**\n * Import policy sets\n * @param {PolicySetExportInterface} importData import data\n * @param {PolicySetImportOptions} options import options\n */\nexport async function importPolicySets({\n importData,\n options = { deps: true, prereqs: false },\n state,\n}: {\n importData: PolicySetExportInterface;\n options?: PolicySetImportOptions;\n state: State;\n}) {\n let response = null;\n const errors = [];\n const imported = [];\n for (const id of Object.keys(importData.policyset)) {\n try {\n const policySetData = importData.policyset[id];\n delete policySetData._rev;\n if (options.prereqs) {\n try {\n await importPolicySetPrerequisites({\n policySetData,\n exportData: importData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n try {\n response = await createPolicySet({ policySetData, state });\n imported.push(id);\n } catch (error) {\n if (error.response?.status === 409) {\n response = await updatePolicySet({ policySetData, state });\n imported.push(id);\n } else throw error;\n }\n if (options.deps) {\n try {\n await importPolicySetDependencies({\n policySetData,\n exportData: importData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Import error:\\n${errorMessages}`);\n }\n if (0 === imported.length) {\n throw new Error(`Import error:\\nNo policy sets found in import data!`);\n }\n return response;\n}\n"]}
1
+ {"version":3,"sources":["../src/ops/PolicySetOps.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EAEf,YAAY,EACZ,eAAe,EACf,eAAe,EAChB,MAAM,qBAAqB,CAAC;AAG7B,OAAO,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,EACL,iBAAiB,EACjB,cAAc,EACd,oBAAoB,EACpB,cAAc,EACf,MAAM,iBAAiB,CAAC;AAUzB,OAAO,KAAK,MAAM,iBAAiB,CAAC;AAEpC,MAAM,CAAC,OAAO,OAAO,YAAY;IAC/B,KAAK,EAAE,KAAK,CAAC;gBACD,KAAK,EAAE,KAAK;IAIxB;;;OAGG;IACG,aAAa,IAAI,OAAO,CAAC,iBAAiB,EAAE,CAAC;IAI7C,YAAY,CAAC,aAAa,EAAE,MAAM;IAIlC,eAAe,CAAC,aAAa,EAAE,iBAAiB;IAIhD,eAAe,CAAC,aAAa,EAAE,iBAAiB;IAIhD,eAAe,CAAC,aAAa,EAAE,MAAM;IAI3C;;;;;OAKG;IACG,eAAe,CACnB,aAAa,EAAE,MAAM,EACrB,OAAO,GAAE,sBAIR,GACA,OAAO,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,wBAAsB,eAAe,CAAC,EACpC,aAAa,EACb,OAIC,EACD,KAAK,GACN,EAAE;IACD,aAAa,EAAE,MAAM,CAAC;IACtB,OAAO,CAAC,EAAE,sBAAsB,CAAC;IACjC,KAAK,EAAE,KAAK,CAAC;CACd,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAuCpC;AAED;;;;GAIG;AACH,wBAAsB,gBAAgB,CAAC,EACrC,OAIC,EACD,KAAK,GACN,EAAE;IACD,OAAO,EAAE,sBAAsB,CAAC;IAChC,KAAK,EAAE,KAAK,CAAC;CACd,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAyCpC;AAkID;;;;;GAKG;AACH,wBAAsB,eAAe,CAAC,EACpC,aAAa,EACb,UAAU,EACV,OAAwC,EACxC,KAAK,GACN,EAAE;IACD,aAAa,EAAE,MAAM,CAAC;IACtB,UAAU,EAAE,wBAAwB,CAAC;IACrC,OAAO,CAAC,EAAE,sBAAsB,CAAC;IACjC,KAAK,EAAE,KAAK,CAAC;CACd,gBAuDA;AAED;;;;GAIG;AACH,wBAAsB,oBAAoB,CAAC,EACzC,UAAU,EACV,OAAwC,EACxC,KAAK,GACN,EAAE;IACD,UAAU,EAAE,wBAAwB,CAAC;IACrC,OAAO,CAAC,EAAE,sBAAsB,CAAC;IACjC,KAAK,EAAE,KAAK,CAAC;CACd,gBAqDA;AAED;;;;GAIG;AACH,wBAAsB,gBAAgB,CAAC,EACrC,UAAU,EACV,OAAwC,EACxC,KAAK,GACN,EAAE;IACD,UAAU,EAAE,wBAAwB,CAAC;IACrC,OAAO,CAAC,EAAE,sBAAsB,CAAC;IACjC,KAAK,EAAE,KAAK,CAAC;CACd,gBAmDA","file":"PolicySetOps.d.ts","sourcesContent":["import {\n deletePolicySet,\n getPolicySets as _getPolicySets,\n getPolicySet,\n createPolicySet,\n updatePolicySet,\n} from '../api/PolicySetApi';\nimport { putScript } from './ScriptOps';\nimport { convertBase64TextToArray } from './utils/ExportImportUtils';\nimport { ExportMetaData } from './OpsTypes';\nimport {\n PolicySetSkeleton,\n PolicySkeleton,\n ResourceTypeSkeleton,\n ScriptSkeleton,\n} from '../api/ApiTypes';\nimport { getMetadata } from './utils/ExportImportUtils';\nimport { debugMessage } from './utils/Console';\nimport { getResourceType, putResourceType } from '../api/ResourceTypesApi';\nimport {\n findScriptUuids,\n getPoliciesByPolicySet,\n getScripts,\n putPolicy,\n} from './PolicyOps';\nimport State from '../shared/State';\n\nexport default class PolicySetOps {\n state: State;\n constructor(state: State) {\n this.state = state;\n }\n\n /**\n * Get all policy sets\n * @returns {Promise} a promise that resolves to an array of policy set objects\n */\n async getPolicySets(): Promise<PolicySetSkeleton[]> {\n return getPolicySets({ state: this.state });\n }\n\n async getPolicySet(policySetName: string) {\n return getPolicySet({ policySetName, state: this.state });\n }\n\n async createPolicySet(policySetData: PolicySetSkeleton) {\n return createPolicySet({ policySetData, state: this.state });\n }\n\n async updatePolicySet(policySetData: PolicySetSkeleton) {\n return updatePolicySet({ policySetData, state: this.state });\n }\n\n async deletePolicySet(policySetName: string) {\n return deletePolicySet({ policySetName, state: this.state });\n }\n\n /**\n * Export policy set\n * @param {string} policySetName policy set name\n * @param {PolicySetExportOptions} options export options\n * @returns {Promise<PolicySetExportInterface>} a promise that resolves to an PolicySetExportInterface object\n */\n async exportPolicySet(\n policySetName: string,\n options: PolicySetExportOptions = {\n deps: true,\n prereqs: false,\n useStringArrays: true,\n }\n ): Promise<PolicySetExportInterface> {\n return exportPolicySet({ policySetName, options, state: this.state });\n }\n\n /**\n * Export policy sets\n * @param {PolicySetExportOptions} options export options\n * @returns {Promise<PolicySetExportInterface>} a promise that resolves to an PolicySetExportInterface object\n */\n async exportPolicySets(\n options: PolicySetExportOptions = {\n deps: true,\n prereqs: false,\n useStringArrays: true,\n }\n ): Promise<PolicySetExportInterface> {\n return exportPolicySets({ options, state: this.state });\n }\n\n /**\n * Import policy set\n * @param {string} policySetName policy set name\n * @param {PolicySetExportInterface} importData import data\n * @param {PolicySetImportOptions} options import options\n */\n async importPolicySet(\n policySetName: string,\n importData: PolicySetExportInterface,\n options: PolicySetImportOptions = { deps: true, prereqs: false }\n ) {\n return importPolicySet({\n policySetName,\n importData,\n options,\n state: this.state,\n });\n }\n\n /**\n * Import first policy set\n * @param {PolicySetExportInterface} importData import data\n * @param {PolicySetImportOptions} options import options\n */\n async importFirstPolicySet(\n importData: PolicySetExportInterface,\n options: PolicySetImportOptions = { deps: true, prereqs: false }\n ) {\n return importFirstPolicySet({ importData, options, state: this.state });\n }\n\n /**\n * Import policy sets\n * @param {PolicySetExportInterface} importData import data\n * @param {PolicySetImportOptions} options import options\n */\n async importPolicySets(\n importData: PolicySetExportInterface,\n options: PolicySetImportOptions = { deps: true, prereqs: false }\n ) {\n return importPolicySets({ importData, options, state: this.state });\n }\n}\n\nexport interface PolicySetExportInterface {\n meta?: ExportMetaData;\n script: Record<string, ScriptSkeleton>;\n resourcetype: Record<string, ResourceTypeSkeleton>;\n policy: Record<string, PolicySkeleton>;\n policyset: Record<string, PolicySetSkeleton>;\n}\n\n/**\n * Application/policy set export options\n */\nexport interface PolicySetExportOptions {\n /**\n * Include any dependencies (policies, scripts, resource types).\n */\n deps: boolean;\n /**\n * Include any prerequisites (policy sets, resource types).\n */\n prereqs: boolean;\n /**\n * Use string arrays to store multi-line text in scripts.\n */\n useStringArrays: boolean;\n}\n\n/**\n * Policy set import options\n */\nexport interface PolicySetImportOptions {\n /**\n * Include any dependencies (policies, scripts, resource types).\n */\n deps: boolean;\n /**\n * Include any prerequisites (policy sets, resource types).\n */\n prereqs: boolean;\n}\n\n/**\n * Create an empty export template\n * @returns {PolicySetExportInterface} an empty export template\n */\nfunction createPolicySetExportTemplate({\n state,\n}: {\n state: State;\n}): PolicySetExportInterface {\n return {\n meta: getMetadata({ state }),\n script: {},\n policy: {},\n resourcetype: {},\n policyset: {},\n } as PolicySetExportInterface;\n}\n\n/**\n * Get all policy sets\n * @returns {Promise} a promise that resolves to an array of policy set objects\n */\nexport async function getPolicySets({\n state,\n}: {\n state: State;\n}): Promise<PolicySetSkeleton[]> {\n const { result } = await _getPolicySets({ state });\n return result;\n}\n\nexport { getPolicySet, createPolicySet, updatePolicySet, deletePolicySet };\n\n/**\n * Helper function to export prerequisites of a policy set\n * @param {PolicySetSkeleton} policySetData policy set object\n * @param {PolicySetExportInterface} exportData export data\n */\nasync function exportPolicySetPrerequisites({\n policySetData,\n exportData,\n state,\n}: {\n policySetData: PolicySetSkeleton;\n exportData: PolicySetExportInterface;\n state: State;\n}) {\n debugMessage({\n message: `PolicySetOps.exportPolicySetPrerequisites: start [policySet=${policySetData['name']}]`,\n state,\n });\n const errors = [];\n // resource types\n for (const resourceTypeUuid of policySetData.resourceTypeUuids) {\n try {\n const resourceType = await getResourceType({ resourceTypeUuid, state });\n exportData.resourcetype[resourceTypeUuid] = resourceType;\n } catch (error) {\n error.message = `Error retrieving resource type ${resourceTypeUuid} for policy set ${policySetData.name}: ${error.message}`;\n errors.push(error);\n }\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Export dependencies error:\\n${errorMessages}`);\n }\n debugMessage({\n message: `PolicySetOps.exportPolicySetPrerequisites: end`,\n state,\n });\n}\n\n/**\n * Helper function to export dependencies of a policy set\n * @param {PolicySetSkeleton} policySetData policy set object\n * @param {PolicySetExportOptions} options export options\n * @param {PolicySetExportInterface} exportData export data\n */\nasync function exportPolicySetDependencies({\n policySetData,\n options,\n exportData,\n state,\n}: {\n policySetData: PolicySetSkeleton;\n options: PolicySetExportOptions;\n exportData: PolicySetExportInterface;\n state: State;\n}) {\n debugMessage({\n message: `PolicySetOps.exportPolicySetDependencies: start [policySet=${policySetData['name']}]`,\n state,\n });\n const errors = [];\n // policies\n try {\n const policies = await getPoliciesByPolicySet({\n policySetId: policySetData.name,\n state,\n });\n for (const policy of policies) {\n exportData.policy[policy.name] = policy;\n // scripts\n try {\n const scripts = await getScripts({ policyData: policy, state });\n for (const scriptData of scripts) {\n if (options.useStringArrays) {\n scriptData.script = convertBase64TextToArray(\n scriptData.script as string\n );\n }\n exportData.script[scriptData._id] = scriptData;\n }\n } catch (error) {\n errors.push(error);\n }\n }\n } catch (error) {\n error.message = `Error retrieving policies in policy set ${policySetData.name}: ${error.message}`;\n errors.push(error);\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Export dependencies error:\\n${errorMessages}`);\n }\n debugMessage({\n message: `PolicySetOps.exportPolicySetDependencies: end`,\n state,\n });\n}\n\n/**\n * Export policy set\n * @param {string} policySetName policy set name\n * @param {PolicySetExportOptions} options export options\n * @returns {Promise<PolicySetExportInterface>} a promise that resolves to an PolicySetExportInterface object\n */\nexport async function exportPolicySet({\n policySetName,\n options = {\n deps: true,\n prereqs: false,\n useStringArrays: true,\n },\n state,\n}: {\n policySetName: string;\n options?: PolicySetExportOptions;\n state: State;\n}): Promise<PolicySetExportInterface> {\n debugMessage({ message: `PolicySetOps.exportPolicySet: start`, state });\n const exportData = createPolicySetExportTemplate({ state });\n const errors = [];\n try {\n const policySetData = await getPolicySet({ policySetName, state });\n exportData.policyset[policySetData.name] = policySetData;\n if (options.prereqs) {\n try {\n await exportPolicySetPrerequisites({\n policySetData,\n exportData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n if (options.deps) {\n try {\n await exportPolicySetDependencies({\n policySetData,\n options,\n exportData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n } catch (error) {\n errors.push(error);\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Export error:\\n${errorMessages}`);\n }\n debugMessage({ message: `PolicySetOps.exportPolicySet: end`, state });\n return exportData;\n}\n\n/**\n * Export policy sets\n * @param {PolicySetExportOptions} options export options\n * @returns {Promise<PolicySetExportInterface>} a promise that resolves to an PolicySetExportInterface object\n */\nexport async function exportPolicySets({\n options = {\n deps: true,\n prereqs: false,\n useStringArrays: true,\n },\n state,\n}: {\n options: PolicySetExportOptions;\n state: State;\n}): Promise<PolicySetExportInterface> {\n debugMessage({ message: `PolicySetOps.exportPolicySet: start`, state });\n const exportData = createPolicySetExportTemplate({ state });\n const errors = [];\n try {\n const policySets = await getPolicySets({ state });\n for (const policySetData of policySets) {\n exportData.policyset[policySetData.name] = policySetData;\n if (options.prereqs) {\n try {\n await exportPolicySetPrerequisites({\n policySetData,\n exportData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n if (options.deps) {\n try {\n await exportPolicySetDependencies({\n policySetData,\n options,\n exportData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n }\n } catch (error) {\n errors.push(error);\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Export error:\\n${errorMessages}`);\n }\n debugMessage({ message: `PolicySetOps.exportPolicySet: end`, state });\n return exportData;\n}\n\n/**\n * Helper function to import prerequisites of a policy set (resource types)\n * @param {PolicySetSkeleton} policySetData policy set data\n * @param {PolicySetExportInterface} exportData export data\n */\nasync function importPolicySetPrerequisites({\n policySetData,\n exportData,\n state,\n}: {\n policySetData: PolicySetSkeleton;\n exportData: PolicySetExportInterface;\n state: State;\n}) {\n debugMessage({\n message: `PolicySetOps.importPolicySetHardDependencies: start [policySet=${policySetData['name']}]`,\n state,\n });\n const errors = [];\n try {\n // resource types\n for (const resourceTypeUuid of policySetData.resourceTypeUuids) {\n if (exportData.resourcetype[resourceTypeUuid]) {\n try {\n debugMessage({\n message: `Importing resource type ${resourceTypeUuid}`,\n state,\n });\n await putResourceType({\n resourceTypeUuid,\n resourceTypeData: exportData.resourcetype[resourceTypeUuid],\n state,\n });\n } catch (error) {\n debugMessage({ message: error.response?.data, state });\n errors.push(error);\n }\n } else {\n errors.push(\n new Error(\n `No resource type definition with id ${resourceTypeUuid} found in import data.`\n )\n );\n }\n }\n } catch (error) {\n error.message = `Error importing hard dependencies for policy set ${policySetData.name}: ${error.message}`;\n errors.push(error);\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Import hard dependencies error:\\n${errorMessages}`);\n }\n debugMessage({\n message: `PolicySetOps.importPolicySetHardDependencies: end`,\n state,\n });\n}\n\n/**\n * Helper function to import dependencies of a policy set (policies and scripts)\n * @param {PolicySetSkeleton} policySetData policy set data\n * @param {PolicySetExportInterface} exportData export data\n */\nasync function importPolicySetDependencies({\n policySetData,\n exportData,\n state,\n}: {\n policySetData: PolicySetSkeleton;\n exportData: PolicySetExportInterface;\n state: State;\n}) {\n debugMessage({\n message: `PolicySetOps.importPolicySetSoftDependencies: start [policySet=${policySetData['name']}]`,\n state,\n });\n const errors = [];\n try {\n // policies\n try {\n const policies = Object.values(exportData.policy).filter(\n (policy) => policy.applicationName === policySetData.name\n );\n for (const policyData of policies) {\n try {\n debugMessage({\n message: `Importing policy ${policyData._id}`,\n state,\n });\n await putPolicy({ policyId: policyData._id, policyData, state });\n } catch (error) {\n debugMessage({ message: error.response?.data, state });\n error.message = `Error importing policy ${policyData._id} in policy set ${policySetData.name}: ${error.message}`;\n errors.push(error);\n }\n // scripts\n const scriptUuids = findScriptUuids(policyData.condition);\n for (const scriptUuid of scriptUuids) {\n try {\n const scriptData = exportData.script[scriptUuid];\n debugMessage({ message: `Importing script ${scriptUuid}`, state });\n await putScript({ scriptId: scriptUuid, scriptData, state });\n } catch (error) {\n debugMessage({ message: error.response?.data, state });\n error.message = `Error importing script ${scriptUuid} for policy ${policyData._id} in policy set ${policySetData.name}: ${error.message}`;\n errors.push(error);\n }\n }\n }\n } catch (error) {\n error.message = `Error importing policies in policy set ${policySetData.name}: ${error.message}`;\n errors.push(error);\n }\n } catch (error) {\n error.message = `Error importing soft dependencies for policy set ${policySetData.name}: ${error.message}`;\n errors.push(error);\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Import soft dependencies error:\\n${errorMessages}`);\n }\n debugMessage({\n message: `PolicySetOps.importPolicySetSoftDependencies: end`,\n state,\n });\n}\n\n/**\n * Import policy set\n * @param {string} policySetName policy set name\n * @param {PolicySetExportInterface} importData import data\n * @param {PolicySetImportOptions} options import options\n */\nexport async function importPolicySet({\n policySetName,\n importData,\n options = { deps: true, prereqs: false },\n state,\n}: {\n policySetName: string;\n importData: PolicySetExportInterface;\n options?: PolicySetImportOptions;\n state: State;\n}) {\n let response = null;\n const errors = [];\n const imported = [];\n for (const id of Object.keys(importData.policyset)) {\n if (id === policySetName) {\n try {\n const policySetData = importData.policyset[id];\n delete policySetData._rev;\n if (options.prereqs) {\n try {\n await importPolicySetPrerequisites({\n policySetData,\n exportData: importData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n try {\n response = await createPolicySet({ policySetData, state });\n imported.push(id);\n } catch (error) {\n if (error.response?.status === 409) {\n response = await updatePolicySet({ policySetData, state });\n imported.push(id);\n } else throw error;\n }\n if (options.deps) {\n try {\n await importPolicySetDependencies({\n policySetData,\n exportData: importData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n } catch (error) {\n errors.push(error);\n }\n }\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Import error:\\n${errorMessages}`);\n }\n if (0 === imported.length) {\n throw new Error(\n `Import error:\\n${policySetName} not found in import data!`\n );\n }\n return response;\n}\n\n/**\n * Import first policy set\n * @param {PolicySetExportInterface} importData import data\n * @param {PolicySetImportOptions} options import options\n */\nexport async function importFirstPolicySet({\n importData,\n options = { deps: true, prereqs: false },\n state,\n}: {\n importData: PolicySetExportInterface;\n options?: PolicySetImportOptions;\n state: State;\n}) {\n let response = null;\n const errors = [];\n const imported = [];\n for (const id of Object.keys(importData.policyset)) {\n try {\n const policySetData = importData.policyset[id];\n delete policySetData._provider;\n delete policySetData._rev;\n if (options.prereqs) {\n try {\n await importPolicySetPrerequisites({\n policySetData,\n exportData: importData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n try {\n response = await createPolicySet({ policySetData, state });\n imported.push(id);\n } catch (error) {\n if (error.response?.status === 409) {\n response = await updatePolicySet({ policySetData, state });\n imported.push(id);\n } else throw error;\n }\n if (options.deps) {\n try {\n await importPolicySetDependencies({\n policySetData,\n exportData: importData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n } catch (error) {\n errors.push(error);\n }\n break;\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Import error:\\n${errorMessages}`);\n }\n if (0 === imported.length) {\n throw new Error(`Import error:\\nNo policy sets found in import data!`);\n }\n return response;\n}\n\n/**\n * Import policy sets\n * @param {PolicySetExportInterface} importData import data\n * @param {PolicySetImportOptions} options import options\n */\nexport async function importPolicySets({\n importData,\n options = { deps: true, prereqs: false },\n state,\n}: {\n importData: PolicySetExportInterface;\n options?: PolicySetImportOptions;\n state: State;\n}) {\n let response = null;\n const errors = [];\n const imported = [];\n for (const id of Object.keys(importData.policyset)) {\n try {\n const policySetData = importData.policyset[id];\n delete policySetData._rev;\n if (options.prereqs) {\n try {\n await importPolicySetPrerequisites({\n policySetData,\n exportData: importData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n try {\n response = await createPolicySet({ policySetData, state });\n imported.push(id);\n } catch (error) {\n if (error.response?.status === 409) {\n response = await updatePolicySet({ policySetData, state });\n imported.push(id);\n } else throw error;\n }\n if (options.deps) {\n try {\n await importPolicySetDependencies({\n policySetData,\n exportData: importData,\n state,\n });\n } catch (error) {\n errors.push(error);\n }\n }\n } catch (error) {\n errors.push(error);\n }\n }\n if (errors.length) {\n const errorMessages = errors.map((error) => error.message).join('\\n');\n throw new Error(`Import error:\\n${errorMessages}`);\n }\n if (0 === imported.length) {\n throw new Error(`Import error:\\nNo policy sets found in import data!`);\n }\n return response;\n}\n"]}