feat(agent): self-heal rustdesk remote access

This commit is contained in:
Esdras Renan 2025-11-11 17:50:09 -03:00
parent 308f7b5712
commit 115d4a62e8
5 changed files with 391 additions and 71 deletions

View file

@ -64,6 +64,7 @@ type AgentConfig = {
machineEmail?: string | null
collaboratorEmail?: string | null
collaboratorName?: string | null
provisioningCode?: string | null
accessRole: "collaborator" | "manager"
assignedUserId?: string | null
assignedUserEmail?: string | null
@ -110,6 +111,50 @@ function normalizeUrl(value?: string | null, fallback = DEFAULT_APP_URL) {
const appUrl = normalizeUrl(import.meta.env.VITE_APP_URL, DEFAULT_APP_URL)
const apiBaseUrl = normalizeUrl(import.meta.env.VITE_API_BASE_URL, appUrl)
const RUSTDESK_SYNC_INTERVAL_MS = 60 * 60 * 1000 // 1h
const TOKEN_SELF_HEAL_DEBOUNCE_MS = 30 * 1000
function sanitizeEmail(value: string | null | undefined) {
const trimmed = (value ?? "").trim().toLowerCase()
return trimmed || null
}
function isTokenRevokedMessage(input: string) {
const normalized = input.toLowerCase()
return (
normalized.includes("token de dispositivo revogado") ||
normalized.includes("token de dispositivo inválido") ||
normalized.includes("token de dispositivo expirado")
)
}
function buildRemoteAccessPayload(info: RustdeskInfo | null) {
if (!info) return null
const payload: Record<string, string | undefined> = {
provider: "RustDesk",
identifier: info.id,
url: `rustdesk://${info.id}`,
password: info.password,
}
if (info.installedVersion) {
payload.notes = `RustDesk ${info.installedVersion}`
}
return payload
}
function buildRemoteAccessSnapshot(info: RustdeskInfo | null) {
const payload = buildRemoteAccessPayload(info)
if (!payload) return null
return {
...payload,
lastVerifiedAt: Date.now(),
metadata: {
source: "raven-desktop",
version: info?.installedVersion ?? null,
},
}
}
async function loadStore(): Promise<Store> {
// Tenta usar uma pasta "data" ao lado do executável (ex.: C:\Raven\data)
try {
@ -217,6 +262,9 @@ function App() {
const [rustdeskInfo, setRustdeskInfo] = useState<RustdeskInfo | null>(null)
const [isRustdeskProvisioning, setIsRustdeskProvisioning] = useState(false)
const rustdeskBootstrapRef = useRef(false)
const rustdeskInfoRef = useRef<RustdeskInfo | null>(null)
const selfHealPromiseRef = useRef<Promise<boolean> | null>(null)
const lastHealAtRef = useRef(0)
const [provisioningCode, setProvisioningCode] = useState("")
const [validatedCompany, setValidatedCompany] = useState<{ id: string; name: string; slug: string; tenantId: string } | null>(null)
@ -236,6 +284,193 @@ function App() {
const emailRegex = useRef(/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/i)
const isEmailValid = useMemo(() => emailRegex.current.test(collabEmail.trim()), [collabEmail])
const ensureProfile = useCallback(async () => {
if (profile) return profile
const fresh = await invoke<MachineProfile>("collect_machine_profile")
setProfile(fresh)
return fresh
}, [profile])
const persistRegistration = useCallback(
async (
data: MachineRegisterResponse,
opts: {
collaborator: { email: string; name?: string | null }
provisioningCode: string
company?: { name?: string | null; slug?: string | null; tenantId?: string | null }
}
) => {
if (!store) throw new Error("Store não carregado")
const resolvedEmail = sanitizeEmail(opts.collaborator.email)
if (!resolvedEmail) {
throw new Error("Informe o e-mail do colaborador para concluir o registro")
}
const collaboratorNameNormalized = opts.collaborator.name?.trim() || null
const companyCtx = opts.company ?? {
name: config?.companyName ?? null,
slug: config?.companySlug ?? null,
tenantId: config?.tenantId ?? null,
}
await writeToken(store, data.machineToken)
setToken(data.machineToken)
const nextConfig: AgentConfig = {
machineId: data.machineId,
tenantId: data.tenantId ?? companyCtx?.tenantId ?? config?.tenantId ?? null,
companySlug: data.companySlug ?? companyCtx?.slug ?? config?.companySlug ?? null,
companyName: companyCtx?.name ?? config?.companyName ?? companyName ?? null,
machineEmail: data.machineEmail ?? null,
collaboratorEmail: resolvedEmail,
collaboratorName: collaboratorNameNormalized,
provisioningCode: opts.provisioningCode,
accessRole: (data.persona ?? config?.accessRole ?? "collaborator").toLowerCase() === "manager" ? "manager" : "collaborator",
assignedUserId: data.assignedUserId ?? null,
assignedUserEmail: data.collaborator?.email ?? resolvedEmail,
assignedUserName: data.collaborator?.name ?? collaboratorNameNormalized,
apiBaseUrl,
appUrl,
createdAt: config?.createdAt ?? Date.now(),
lastSyncedAt: Date.now(),
expiresAt: data.expiresAt ?? null,
heartbeatIntervalSec: config?.heartbeatIntervalSec ?? null,
}
setConfig(nextConfig)
setCompanyName(nextConfig.companyName ?? "")
setCollabEmail(resolvedEmail)
setCollabName(collaboratorNameNormalized ?? "")
setProvisioningCode(opts.provisioningCode)
await writeConfig(store, nextConfig)
tokenVerifiedRef.current = true
setStatus("online")
setIsMachineActive(true)
setTokenValidationTick((tick) => tick + 1)
try {
await invoke("start_machine_agent", {
baseUrl: apiBaseUrl,
token: data.machineToken,
status: "online",
intervalSeconds: nextConfig.heartbeatIntervalSec ?? 300,
})
} catch (err) {
console.error("Falha ao reiniciar heartbeat", err)
}
return nextConfig
},
[store, config, companyName]
)
const reRegisterMachine = useCallback(
async (context: string) => {
if (!store) return false
const storedCode = (config?.provisioningCode ?? provisioningCode).trim().toLowerCase()
if (!storedCode) {
console.warn("[self-heal] Provisioning code absent; manual intervention required")
setError("Código de provisionamento ausente. Informe-o novamente para concluir o processo.")
return false
}
const collaboratorEmail = sanitizeEmail(collabEmail) ?? config?.collaboratorEmail ?? config?.assignedUserEmail ?? null
if (!collaboratorEmail) {
console.warn("[self-heal] Collaborator email missing")
setError("Informe o e-mail do colaborador vinculado a esta dispositivo para continuar.")
return false
}
const collaboratorName = collabName.trim() || config?.collaboratorName || config?.assignedUserName || null
let machineProfile: MachineProfile
try {
machineProfile = await ensureProfile()
} catch (profileError) {
console.error("[self-heal] Falha ao coletar perfil", profileError)
setError("Não foi possível coletar os dados da dispositivo para reprovisionar. Reabra o app como administrador.")
return false
}
const metadataPayload: Record<string, unknown> = {
inventory: machineProfile.inventory,
metrics: machineProfile.metrics,
collaborator: {
email: collaboratorEmail,
name: collaboratorName,
role: config?.accessRole ?? "collaborator",
},
}
const snapshot = buildRemoteAccessSnapshot(rustdeskInfoRef.current)
if (snapshot) {
metadataPayload.remoteAccessSnapshot = snapshot
}
const body = {
provisioningCode: storedCode,
hostname: machineProfile.hostname,
os: machineProfile.os,
macAddresses: machineProfile.mac_addresses,
serialNumbers: machineProfile.serial_numbers,
metadata: metadataPayload,
collaborator: {
email: collaboratorEmail,
name: collaboratorName ?? undefined,
},
registeredBy: "desktop-agent",
}
try {
const res = await fetch(`${apiBaseUrl}/api/machines/register`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
})
if (!res.ok) {
const text = await res.text()
console.error(`[self-heal] Reprovision failed (${context})`, text)
setError("Falha ao reprovisionar automaticamente. Revise o código e tente novamente.")
return false
}
const data = (await res.json()) as MachineRegisterResponse
await persistRegistration(data, {
collaborator: { email: collaboratorEmail, name: collaboratorName },
provisioningCode: storedCode,
company: {
name: config?.companyName ?? validatedCompany?.name ?? null,
slug: config?.companySlug ?? validatedCompany?.slug ?? null,
tenantId: config?.tenantId ?? validatedCompany?.tenantId ?? null,
},
})
console.info(`[self-heal] Token regenerado (${context})`)
return true
} catch (error) {
console.error(`[self-heal] Erro inesperado (${context})`, error)
setError("Não foi possível reprovisionar automaticamente. Verifique a conexão e tente novamente.")
return false
}
},
[store, config, provisioningCode, collabEmail, collabName, ensureProfile, persistRegistration, validatedCompany]
)
const attemptSelfHeal = useCallback(
async (context: string) => {
if (!store) return false
if (selfHealPromiseRef.current) {
return selfHealPromiseRef.current
}
const elapsed = Date.now() - lastHealAtRef.current
if (elapsed < TOKEN_SELF_HEAL_DEBOUNCE_MS && lastHealAtRef.current !== 0) {
return false
}
const promise = reRegisterMachine(context).finally(() => {
selfHealPromiseRef.current = null
lastHealAtRef.current = Date.now()
})
selfHealPromiseRef.current = promise
return promise
},
[store, reRegisterMachine]
)
useEffect(() => {
(async () => {
try {
@ -268,10 +503,18 @@ function App() {
;(async () => {
setIsValidatingToken(true)
try {
const snapshot = buildRemoteAccessSnapshot(rustdeskInfoRef.current)
const heartbeatPayload: Record<string, unknown> = {
machineToken: token,
status: "online",
}
if (snapshot) {
heartbeatPayload.metadata = { remoteAccessSnapshot: snapshot }
}
const res = await fetch(`${apiBaseUrl}/api/machines/heartbeat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ machineToken: token, status: "online" }),
body: JSON.stringify(heartbeatPayload),
})
if (cancelled) return
if (res.ok) {
@ -305,6 +548,12 @@ function App() {
msg.includes("token de dispositivo revogado") ||
msg.includes("token de dispositivo expirado")
if (isInvalid) {
const healed = await attemptSelfHeal("heartbeat")
if (cancelled) return
if (healed) {
setStatus("online")
return
}
try {
await store.delete("token"); await store.delete("config"); await store.save()
} catch {}
@ -338,10 +587,10 @@ function App() {
return () => {
cancelled = true
}
}, [store, token])
}, [store, token, attemptSelfHeal])
useEffect(() => {
if (!import.meta.env.DEV) return
useEffect(() => {
if (!import.meta.env.DEV) return
function onKeyDown(event: KeyboardEvent) {
const key = (event.key || "").toLowerCase()
@ -364,7 +613,11 @@ function App() {
window.removeEventListener("keydown", onKeyDown)
window.removeEventListener("contextmenu", onContextMenu)
}
}, [])
}, [])
useEffect(() => {
rustdeskInfoRef.current = rustdeskInfo
}, [rustdeskInfo])
useEffect(() => {
if (!store || !config) return
@ -387,6 +640,12 @@ function App() {
writeConfig(store, nextConfig).catch((err) => console.error("Falha ao atualizar colaborador", err))
}, [store, config, config?.collaboratorEmail, config?.collaboratorName, collabEmail, collabName])
useEffect(() => {
if (!config?.provisioningCode) return
if (provisioningCode.trim()) return
setProvisioningCode(config.provisioningCode)
}, [config?.provisioningCode, provisioningCode])
useEffect(() => {
if (!store || !config) return
const normalizedAppUrl = normalizeUrl(config.appUrl, appUrl)
@ -463,35 +722,45 @@ const resolvedAppUrl = useMemo(() => {
return normalized
}, [config?.appUrl])
const syncRustdeskAccess = useCallback(
async (machineToken: string, info: RustdeskInfo) => {
if (!store || !machineToken) return
try {
const response = await fetch(`${apiBaseUrl}/api/machines/remote-access`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
machineToken,
provider: "RustDesk",
identifier: info.id,
url: `rustdesk://${info.id}`,
password: info.password,
notes: info.installedVersion ? `RustDesk ${info.installedVersion}` : undefined,
}),
})
if (!response.ok) {
const text = await response.text()
throw new Error(text.slice(0, 300) || "Falha ao registrar acesso remoto")
const syncRustdeskAccess = useCallback(
async (machineToken: string, info: RustdeskInfo, allowRetry = true) => {
if (!store || !machineToken) return
const payload = buildRemoteAccessPayload(info)
if (!payload) return
try {
const response = await fetch(`${apiBaseUrl}/api/machines/remote-access`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ machineToken, ...payload }),
})
if (!response.ok) {
const text = await response.text()
if (allowRetry && isTokenRevokedMessage(text)) {
const healed = await attemptSelfHeal("remote-access")
if (healed) {
const refreshedToken = (await readToken(store)) ?? machineToken
return syncRustdeskAccess(refreshedToken, info, false)
}
}
throw new Error(text.slice(0, 300) || "Falha ao registrar acesso remoto")
}
const nextInfo: RustdeskInfo = { ...info, lastSyncedAt: Date.now() }
await writeRustdeskInfo(store, nextInfo)
setRustdeskInfo(nextInfo)
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
if (allowRetry && isTokenRevokedMessage(message)) {
const healed = await attemptSelfHeal("remote-access")
if (healed) {
const refreshedToken = (await readToken(store)) ?? machineToken
return syncRustdeskAccess(refreshedToken, info, false)
}
}
console.error("Falha ao sincronizar acesso remoto com a plataforma", error)
}
const nextInfo: RustdeskInfo = { ...info, lastSyncedAt: Date.now() }
await writeRustdeskInfo(store, nextInfo)
setRustdeskInfo(nextInfo)
} catch (error) {
console.error("Falha ao sincronizar acesso remoto com a plataforma", error)
}
},
[store]
)
},
[store, attemptSelfHeal]
)
const provisionRustdesk = useCallback(
async (machineId: string, machineToken: string): Promise<RustdeskInfo | null> => {
@ -536,7 +805,7 @@ useEffect(() => {
}
if (rustdeskInfo && !isRustdeskProvisioning) {
const lastSync = rustdeskInfo.lastSyncedAt ?? 0
const needsSync = Date.now() - lastSync > 7 * 24 * 60 * 60 * 1000
const needsSync = Date.now() - lastSync > RUSTDESK_SYNC_INTERVAL_MS
if (needsSync) {
syncRustdeskAccess(token, rustdeskInfo)
}
@ -581,6 +850,10 @@ useEffect(() => {
metrics: profile.metrics,
collaborator: { email: normalizedEmail, name: normalizedName, role: "collaborator" },
}
const bootstrapSnapshot = buildRemoteAccessSnapshot(rustdeskInfoRef.current)
if (bootstrapSnapshot) {
metadataPayload.remoteAccessSnapshot = bootstrapSnapshot
}
const payload = {
provisioningCode: trimmedCode,
@ -604,45 +877,18 @@ useEffect(() => {
}
const data = (await res.json()) as MachineRegisterResponse
if (!store) throw new Error("Store ausente")
await writeToken(store, data.machineToken)
const cfg: AgentConfig = {
machineId: data.machineId,
tenantId: data.tenantId ?? validatedCompany.tenantId ?? null,
companySlug: data.companySlug ?? validatedCompany.slug ?? null,
companyName: validatedCompany.name,
machineEmail: data.machineEmail ?? null,
collaboratorEmail: collaboratorPayload.email,
collaboratorName: collaboratorPayload.name,
accessRole: "collaborator",
assignedUserId: data.assignedUserId ?? null,
assignedUserEmail: data.collaborator?.email ?? collaboratorPayload.email,
assignedUserName: data.collaborator?.name ?? collaboratorPayload.name,
apiBaseUrl,
appUrl,
createdAt: Date.now(),
lastSyncedAt: Date.now(),
expiresAt: data.expiresAt ?? null,
}
await writeConfig(store, cfg)
setConfig(cfg)
setToken(data.machineToken)
setCompanyName(validatedCompany.name)
await persistRegistration(data, {
collaborator: collaboratorPayload,
provisioningCode: trimmedCode,
company: {
name: validatedCompany.name,
slug: validatedCompany.slug,
tenantId: validatedCompany.tenantId,
},
})
await provisionRustdesk(data.machineId, data.machineToken)
await invoke("start_machine_agent", {
baseUrl: apiBaseUrl,
token: data.machineToken,
status: "online",
intervalSeconds: 300,
})
setStatus("online")
tokenVerifiedRef.current = true
// Abre o sistema imediatamente após registrar (evita ficar com token inválido no fluxo antigo)
try {
await fetch(`${apiBaseUrl}/api/machines/sessions`, {