Edits history of script submission #24095 for ' List alerts (netskope)'

  • bunnative
    One script reply has been approved by the moderators
    Ap­pro­ved
    //native
    
    /**
     * List alerts
     * List alerts raised in a time window, one page at a time. Pass next_offset back as offset to fetch the next page.
     */
    export async function main(
      auth: RT.Netskope,
      start_time: string,
      end_time: string | undefined,
      limit: number | undefined,
      offset: number | undefined,
      alert_type: string | undefined,
      query: string | undefined,
      fields: string | undefined
    ) {
      const toEpoch = (value: string) => {
        const ms = Date.parse(value)
        if (Number.isNaN(ms)) {
          throw new Error(`Invalid date: ${value}`)
        }
        return Math.floor(ms / 1000).toString()
      }
      const pageSize = limit || 100
      if (pageSize > 10000) {
        throw new Error("limit cannot exceed 10000 (datasearch page cap)")
      }
      const skip = offset || 0
    
      const filters: string[] = []
      if (query != null && query !== "") {
        filters.push(query)
      }
      if (alert_type != null && alert_type !== "") {
        if (!/^[a-zA-Z0-9_ -]+$/.test(alert_type)) {
          throw new Error(`Invalid alert_type: ${alert_type}`)
        }
        filters.push(`alert_type eq "${alert_type}"`)
      }
    
      const url = new URL(
        `${auth.tenant_url.replace(/\/+$/, "")}/api/v2/events/datasearch/alert`
      )
      url.searchParams.append("starttime", toEpoch(start_time))
      url.searchParams.append(
        "endtime",
        end_time ? toEpoch(end_time) : Math.floor(Date.now() / 1000).toString()
      )
      url.searchParams.append("limit", pageSize.toString())
      url.searchParams.append("offset", skip.toString())
      if (filters.length) {
        url.searchParams.append("query", filters.join(" AND "))
      }
      if (fields != null && fields !== "") {
        url.searchParams.append("fields", fields)
      }
    
      const response = await fetch(url, {
        method: "GET",
        headers: {
          "Netskope-Api-Token": auth.token,
          Accept: "application/json",
        },
      })
    
      if (!response.ok) {
        throw new Error(`${response.status} ${await response.text()}`)
      }
    
      const page = (await response.json()) as {
        result?: unknown[]
        status?: { execution?: string; total?: number }
      }
      if (page.status?.execution === "FAILED") {
        throw new Error(`Netskope query failed: ${JSON.stringify(page.status)}`)
      }
      const count = page.result?.length ?? 0
      const total = page.status?.total
      const hasMore = total != null ? skip + count < total : count === pageSize
      return {
        ...page,
        next_offset: hasMore && count > 0 ? skip + count : null,
      }
    }
    

    Submitted by hugo989 7 hours ago