Edits history of script submission #24116 for ' List policy packages (fortimanager)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * List policy packages
     * List the policy packages of an ADOM. Packages inside folders are flattened with their full path (folder/subfolder/package), which is the name install_policy_package expects; the raw tree is returned too.
     */
    export async function main(auth: RT.Fortimanager, adom: string) {
      // The ADOM is a segment of the JSON-RPC url: a "/" would address another table.
      if (adom.includes("/")) throw new Error(`Invalid adom: ${adom}`)
      const response = await fetch(`${auth.base_url.replace(/\/+$/, "")}/jsonrpc`, {
        method: "POST",
        headers: {
          Authorization: `Bearer ${auth.token}`,
          "Content-Type": "application/json",
          Accept: "application/json",
        },
        body: JSON.stringify({
          id: 1,
          method: "get",
          params: [{ url: `/pm/pkg/adom/${adom}` }],
          verbose: 1,
        }),
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      const json = await response.json()
      const result = json.result?.[0]
      if (result?.status?.code !== 0) {
        throw new Error(
          `FortiManager error: ${JSON.stringify(json.result ?? json)}`
        )
      }
    
      // Folders have type "folder" and hold their children in "subobj".
      const packages: {
        path: string
        name: string
        oid: number
        scope_member: any[]
      }[] = []
      const walk = (nodes: any[], prefix: string) => {
        for (const node of nodes ?? []) {
          const path = prefix ? `${prefix}/${node.name}` : node.name
          if (node.type === "folder") {
            walk(node.subobj, path)
          } else {
            packages.push({
              path,
              name: node.name,
              oid: node.oid,
              scope_member: node["scope member"] ?? [],
            })
          }
        }
      }
      walk(result.data ?? [], "")
    
      return { packages, tree: result.data ?? [] }
    }
    

    Submitted by hugo989 6 hours ago