//native
import * as wmill from "windmill-client"
async function getManagementToken(auth: RT.Auth0): Promise<string> {
const response = await fetch(`https://${auth.domain}/oauth/token`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
grant_type: "client_credentials",
client_id: auth.client_id,
client_secret: auth.client_secret,
audience: `https://${auth.domain}/api/v2/`,
}),
})
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`)
}
const { access_token } = (await response.json()) as { access_token: string }
return access_token
}
/**
* New Log Event
* Emits new tenant log events (logins, errors, admin changes) since the last run, using Auth0 checkpoint pagination. The first run records the current position and returns nothing.
*/
export async function main(auth: RT.Auth0) {
const token = await getManagementToken(auth)
const lastLogId: string | undefined = await wmill.getState()
// Bootstrap: record the latest log id and emit nothing on the first run.
if (!lastLogId) {
const bootstrapUrl = new URL(`https://${auth.domain}/api/v2/logs`)
bootstrapUrl.searchParams.append("take", "1")
bootstrapUrl.searchParams.append("sort", "date:-1")
const bootstrapResponse = await fetch(bootstrapUrl, {
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
},
})
if (!bootstrapResponse.ok) {
throw new Error(
`${bootstrapResponse.status} ${await bootstrapResponse.text()}`
)
}
const latest = (await bootstrapResponse.json()) as { log_id: string }[]
if (latest.length > 0) await wmill.setState(latest[0].log_id)
return []
}
const url = new URL(`https://${auth.domain}/api/v2/logs`)
url.searchParams.append("from", lastLogId)
url.searchParams.append("take", "100")
const response = await fetch(url, {
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/json",
},
})
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`)
}
const logs = (await response.json()) as { log_id: string }[]
if (logs.length > 0) await wmill.setState(logs[logs.length - 1].log_id)
return logs
}
Submitted by hugo989 5 days ago