feat: adicionar painel de máquinas e autenticação por agente

This commit is contained in:
Esdras Renan 2025-10-07 21:37:41 -03:00
parent e2a5b560b1
commit ee18619519
52 changed files with 7598 additions and 1 deletions

24
apps/desktop/.gitignore vendored Normal file
View file

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

3
apps/desktop/.vscode/extensions.json vendored Normal file
View file

@ -0,0 +1,3 @@
{
"recommendations": ["tauri-apps.tauri-vscode", "rust-lang.rust-analyzer"]
}

7
apps/desktop/README.md Normal file
View file

@ -0,0 +1,7 @@
# Tauri + Vanilla TS
This template should help get you started developing with Tauri in vanilla HTML, CSS and Typescript.
## Recommended IDE Setup
- [VS Code](https://code.visualstudio.com/) + [Tauri](https://marketplace.visualstudio.com/items?itemName=tauri-apps.tauri-vscode) + [rust-analyzer](https://marketplace.visualstudio.com/items?itemName=rust-lang.rust-analyzer)

19
apps/desktop/index.html Normal file
View file

@ -0,0 +1,19 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="/src/styles.css" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Sistema de Chamados Desktop</title>
<script type="module" src="/src/main.ts" defer></script>
</head>
<body>
<main style="height: 100vh; display: grid; place-items: center;">
<div style="text-align: center; font-family: system-ui, sans-serif;">
<h1 style="margin-bottom: 0.5rem;">Abrindo Sistema de Chamados…</h1>
<p style="color: #555;">Certifique-se de que o serviço web está disponível em <code>VITE_APP_URL</code>.</p>
</div>
</main>
</body>
</html>

21
apps/desktop/package.json Normal file
View file

@ -0,0 +1,21 @@
{
"name": "appsdesktop",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"tauri": "tauri"
},
"dependencies": {
"@tauri-apps/api": "^2",
"@tauri-apps/plugin-opener": "^2"
},
"devDependencies": {
"@tauri-apps/cli": "^2",
"vite": "^6.0.3",
"typescript": "~5.6.2"
}
}

7
apps/desktop/src-tauri/.gitignore vendored Normal file
View file

@ -0,0 +1,7 @@
# Generated by Cargo
# will have compiled files and executables
/target/
# Generated by Tauri
# will have schema files for capabilities auto-completion
/gen/schemas

5311
apps/desktop/src-tauri/Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,25 @@
[package]
name = "appsdesktop"
version = "0.1.0"
description = "A Tauri App"
authors = ["you"]
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[lib]
# The `_lib` suffix may seem redundant but it is necessary
# to make the lib name unique and wouldn't conflict with the bin name.
# This seems to be only an issue on Windows, see https://github.com/rust-lang/cargo/issues/8519
name = "appsdesktop_lib"
crate-type = ["staticlib", "cdylib", "rlib"]
[build-dependencies]
tauri-build = { version = "2", features = [] }
[dependencies]
tauri = { version = "2", features = [] }
tauri-plugin-opener = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"

View file

@ -0,0 +1,3 @@
fn main() {
tauri_build::build()
}

View file

@ -0,0 +1,10 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "Capability for the main window",
"windows": ["main"],
"permissions": [
"core:default",
"opener:default"
]
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 974 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 903 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

View file

@ -0,0 +1,14 @@
// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
#[tauri::command]
fn greet(name: &str) -> String {
format!("Hello, {}! You've been greeted from Rust!", name)
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_opener::init())
.invoke_handler(tauri::generate_handler![greet])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}

View file

@ -0,0 +1,6 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
appsdesktop_lib::run()
}

View file

@ -0,0 +1,36 @@
{
"$schema": "https://schema.tauri.app/config/2",
"productName": "appsdesktop",
"version": "0.1.0",
"identifier": "com.renan.appsdesktop",
"build": {
"beforeDevCommand": "",
"devUrl": "http://localhost:3000",
"beforeBuildCommand": "",
"frontendDist": ""
},
"app": {
"withGlobalTauri": true,
"windows": [
{
"title": "appsdesktop",
"width": 800,
"height": 600
}
],
"security": {
"csp": null
}
},
"bundle": {
"active": true,
"targets": "all",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
]
}
}

View file

@ -0,0 +1,6 @@
<svg width="206" height="231" viewBox="0 0 206 231" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M143.143 84C143.143 96.1503 133.293 106 121.143 106C108.992 106 99.1426 96.1503 99.1426 84C99.1426 71.8497 108.992 62 121.143 62C133.293 62 143.143 71.8497 143.143 84Z" fill="#FFC131"/>
<ellipse cx="84.1426" cy="147" rx="22" ry="22" transform="rotate(180 84.1426 147)" fill="#24C8DB"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M166.738 154.548C157.86 160.286 148.023 164.269 137.757 166.341C139.858 160.282 141 153.774 141 147C141 144.543 140.85 142.121 140.558 139.743C144.975 138.204 149.215 136.139 153.183 133.575C162.73 127.404 170.292 118.608 174.961 108.244C179.63 97.8797 181.207 86.3876 179.502 75.1487C177.798 63.9098 172.884 53.4021 165.352 44.8883C157.82 36.3744 147.99 30.2165 137.042 27.1546C126.095 24.0926 114.496 24.2568 103.64 27.6274C92.7839 30.998 83.1319 37.4317 75.8437 46.1553C74.9102 47.2727 74.0206 48.4216 73.176 49.5993C61.9292 50.8488 51.0363 54.0318 40.9629 58.9556C44.2417 48.4586 49.5653 38.6591 56.679 30.1442C67.0505 17.7298 80.7861 8.57426 96.2354 3.77762C111.685 -1.01901 128.19 -1.25267 143.769 3.10474C159.348 7.46215 173.337 16.2252 184.056 28.3411C194.775 40.457 201.767 55.4101 204.193 71.404C206.619 87.3978 204.374 103.752 197.73 118.501C191.086 133.25 180.324 145.767 166.738 154.548ZM41.9631 74.275L62.5557 76.8042C63.0459 72.813 63.9401 68.9018 65.2138 65.1274C57.0465 67.0016 49.2088 70.087 41.9631 74.275Z" fill="#FFC131"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M38.4045 76.4519C47.3493 70.6709 57.2677 66.6712 67.6171 64.6132C65.2774 70.9669 64 77.8343 64 85.0001C64 87.1434 64.1143 89.26 64.3371 91.3442C60.0093 92.8732 55.8533 94.9092 51.9599 97.4256C42.4128 103.596 34.8505 112.392 30.1816 122.756C25.5126 133.12 23.9357 144.612 25.6403 155.851C27.3449 167.09 32.2584 177.598 39.7906 186.112C47.3227 194.626 57.153 200.784 68.1003 203.846C79.0476 206.907 90.6462 206.743 101.502 203.373C112.359 200.002 122.011 193.568 129.299 184.845C130.237 183.722 131.131 182.567 131.979 181.383C143.235 180.114 154.132 176.91 164.205 171.962C160.929 182.49 155.596 192.319 148.464 200.856C138.092 213.27 124.357 222.426 108.907 227.222C93.458 232.019 76.9524 232.253 61.3736 227.895C45.7948 223.538 31.8055 214.775 21.0867 202.659C10.3679 190.543 3.37557 175.59 0.949823 159.596C-1.47592 143.602 0.768139 127.248 7.41237 112.499C14.0566 97.7497 24.8183 85.2327 38.4045 76.4519ZM163.062 156.711L163.062 156.711C162.954 156.773 162.846 156.835 162.738 156.897C162.846 156.835 162.954 156.773 163.062 156.711Z" fill="#24C8DB"/>
</svg>

After

Width:  |  Height:  |  Size: 2.5 KiB

View file

@ -0,0 +1,25 @@
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg version="1.0" xmlns="http://www.w3.org/2000/svg"
width="512.000000pt" height="512.000000pt" viewBox="0 0 512.000000 512.000000"
preserveAspectRatio="xMidYMid meet">
<g transform="translate(0.000000,512.000000) scale(0.100000,-0.100000)"
fill="#2D79C7" stroke="none">
<path d="M430 5109 c-130 -19 -248 -88 -325 -191 -53 -71 -83 -147 -96 -247
-6 -49 -9 -813 -7 -2166 l3 -2090 22 -65 c54 -159 170 -273 328 -323 l70 -22
2140 0 2140 0 66 23 c160 55 272 169 322 327 l22 70 0 2135 0 2135 -22 70
c-49 157 -155 265 -319 327 l-59 23 -2115 1 c-1163 1 -2140 -2 -2170 -7z
m3931 -2383 c48 -9 120 -26 160 -39 l74 -23 3 -237 c1 -130 0 -237 -2 -237 -3
0 -26 14 -53 30 -61 38 -197 84 -310 106 -110 20 -293 15 -368 -12 -111 -39
-175 -110 -175 -193 0 -110 97 -197 335 -300 140 -61 309 -146 375 -189 30
-20 87 -68 126 -107 119 -117 164 -234 164 -426 0 -310 -145 -518 -430 -613
-131 -43 -248 -59 -445 -60 -243 -1 -405 24 -577 90 l-68 26 0 242 c0 175 -3
245 -12 254 -9 9 -9 12 0 12 7 0 12 -4 12 -9 0 -17 139 -102 223 -138 136 -57
233 -77 382 -76 145 0 224 19 295 68 75 52 100 156 59 242 -41 84 -135 148
-374 253 -367 161 -522 300 -581 520 -23 86 -23 253 -1 337 73 275 312 448
682 492 109 13 401 6 506 -13z m-1391 -241 l0 -205 -320 0 -320 0 0 -915 0
-915 -255 0 -255 0 0 915 0 915 -320 0 -320 0 0 205 0 205 895 0 895 0 0 -205z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="31.88" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 257"><defs><linearGradient id="IconifyId1813088fe1fbc01fb466" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"></stop><stop offset="100%" stop-color="#BD34FE"></stop></linearGradient><linearGradient id="IconifyId1813088fe1fbc01fb467" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"></stop><stop offset="8.333%" stop-color="#FFDD35"></stop><stop offset="100%" stop-color="#FFA800"></stop></linearGradient></defs><path fill="url(#IconifyId1813088fe1fbc01fb466)" d="M255.153 37.938L134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"></path><path fill="url(#IconifyId1813088fe1fbc01fb467)" d="M185.432.063L96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

30
apps/desktop/src/main.ts Normal file
View file

@ -0,0 +1,30 @@
declare global {
interface ImportMetaEnv {
readonly VITE_APP_URL?: string
}
interface ImportMeta {
readonly env: ImportMetaEnv
}
}
const DEFAULT_URL = "http://localhost:3000";
function resolveTargetUrl() {
const fromEnv = import.meta?.env?.VITE_APP_URL;
if (fromEnv && fromEnv.trim().length > 0) {
return fromEnv.trim();
}
return DEFAULT_URL;
}
function bootstrap() {
const targetUrl = resolveTargetUrl();
if (!targetUrl.startsWith("http")) {
console.error("URL inválida para o app desktop:", targetUrl);
return;
}
window.location.replace(targetUrl);
}
document.addEventListener("DOMContentLoaded", bootstrap);

116
apps/desktop/src/styles.css Normal file
View file

@ -0,0 +1,116 @@
.logo.vite:hover {
filter: drop-shadow(0 0 2em #747bff);
}
.logo.typescript:hover {
filter: drop-shadow(0 0 2em #2d79c7);
}
:root {
font-family: Inter, Avenir, Helvetica, Arial, sans-serif;
font-size: 16px;
line-height: 24px;
font-weight: 400;
color: #0f0f0f;
background-color: #f6f6f6;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
}
.container {
margin: 0;
padding-top: 10vh;
display: flex;
flex-direction: column;
justify-content: center;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: 0.75s;
}
.logo.tauri:hover {
filter: drop-shadow(0 0 2em #24c8db);
}
.row {
display: flex;
justify-content: center;
}
a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}
h1 {
text-align: center;
}
input,
button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
color: #0f0f0f;
background-color: #ffffff;
transition: border-color 0.25s;
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.2);
}
button {
cursor: pointer;
}
button:hover {
border-color: #396cd8;
}
button:active {
border-color: #396cd8;
background-color: #e8e8e8;
}
input,
button {
outline: none;
}
#greet-input {
margin-right: 5px;
}
@media (prefers-color-scheme: dark) {
:root {
color: #f6f6f6;
background-color: #2f2f2f;
}
a:hover {
color: #24c8db;
}
input,
button {
color: #ffffff;
background-color: #0f0f0f98;
}
button:active {
background-color: #0f0f0f69;
}
}

View file

@ -0,0 +1,23 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}

View file

@ -0,0 +1,31 @@
// @ts-nocheck
import { defineConfig } from "vite";
const host = process.env.TAURI_DEV_HOST;
// https://vite.dev/config/
export default defineConfig(async () => ({
// Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
//
// 1. prevent Vite from obscuring rust errors
clearScreen: false,
// 2. tauri expects a fixed port, fail if that port is not available
server: {
port: 1420,
strictPort: true,
host: host || false,
hmr: host
? {
protocol: "ws",
host,
port: 1421,
}
: undefined,
watch: {
// 3. tell Vite to ignore watching `src-tauri`
ignored: ["**/src-tauri/**"],
},
},
}));

View file

@ -18,6 +18,7 @@ import type * as crons from "../crons.js";
import type * as fields from "../fields.js"; import type * as fields from "../fields.js";
import type * as files from "../files.js"; import type * as files from "../files.js";
import type * as invites from "../invites.js"; import type * as invites from "../invites.js";
import type * as machines from "../machines.js";
import type * as migrations from "../migrations.js"; import type * as migrations from "../migrations.js";
import type * as queues from "../queues.js"; import type * as queues from "../queues.js";
import type * as rbac from "../rbac.js"; import type * as rbac from "../rbac.js";
@ -53,6 +54,7 @@ declare const fullApi: ApiFromModules<{
fields: typeof fields; fields: typeof fields;
files: typeof files; files: typeof files;
invites: typeof invites; invites: typeof invites;
machines: typeof machines;
migrations: typeof migrations; migrations: typeof migrations;
queues: typeof queues; queues: typeof queues;
rbac: typeof rbac; rbac: typeof rbac;

504
convex/machines.ts Normal file
View file

@ -0,0 +1,504 @@
import { mutation, query } from "./_generated/server"
import { ConvexError, v } from "convex/values"
import { sha256 } from "@noble/hashes/sha256"
import { randomBytes } from "@noble/hashes/utils"
import type { Doc, Id } from "./_generated/dataModel"
import type { MutationCtx } from "./_generated/server"
const DEFAULT_TENANT_ID = "tenant-atlas"
const DEFAULT_TOKEN_TTL_MS = 1000 * 60 * 60 * 24 * 30 // 30 dias
type NormalizedIdentifiers = {
macs: string[]
serials: string[]
}
function getProvisioningSecret() {
const secret = process.env.MACHINE_PROVISIONING_SECRET
if (!secret) {
throw new ConvexError("Provisionamento de máquinas não configurado")
}
return secret
}
function getTokenTtlMs(): number {
const raw = process.env.MACHINE_TOKEN_TTL_MS
if (!raw) return DEFAULT_TOKEN_TTL_MS
const parsed = Number(raw)
if (!Number.isFinite(parsed) || parsed < 60_000) {
return DEFAULT_TOKEN_TTL_MS
}
return parsed
}
function normalizeIdentifiers(macAddresses: string[], serialNumbers: string[]): NormalizedIdentifiers {
const normalizeMac = (value: string) => value.replace(/[^a-f0-9]/gi, "").toLowerCase()
const normalizeSerial = (value: string) => value.trim().toLowerCase()
const macs = Array.from(new Set(macAddresses.map(normalizeMac).filter(Boolean))).sort()
const serials = Array.from(new Set(serialNumbers.map(normalizeSerial).filter(Boolean))).sort()
if (macs.length === 0 && serials.length === 0) {
throw new ConvexError("Informe ao menos um identificador (MAC ou serial)")
}
return { macs, serials }
}
function toHex(input: Uint8Array) {
return Array.from(input)
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("")
}
function computeFingerprint(tenantId: string, companySlug: string | undefined, hostname: string, ids: NormalizedIdentifiers) {
const payload = JSON.stringify({
tenantId,
companySlug: companySlug ?? null,
hostname: hostname.trim().toLowerCase(),
macs: ids.macs,
serials: ids.serials,
})
return toHex(sha256(payload))
}
function hashToken(token: string) {
return toHex(sha256(token))
}
async function ensureCompany(
ctx: MutationCtx,
tenantId: string,
companySlug?: string
): Promise<{ companyId?: Id<"companies">; companySlug?: string }> {
if (!companySlug) return {}
const company = await ctx.db
.query("companies")
.withIndex("by_tenant_slug", (q: any) => q.eq("tenantId", tenantId).eq("slug", companySlug))
.unique()
if (!company) {
throw new ConvexError("Empresa não encontrada para o tenant informado")
}
return { companyId: company._id, companySlug: company.slug }
}
async function getActiveToken(
ctx: MutationCtx,
tokenValue: string
): Promise<{ token: Doc<"machineTokens">; machine: Doc<"machines"> }> {
const tokenHash = hashToken(tokenValue)
const token = await ctx.db
.query("machineTokens")
.withIndex("by_token_hash", (q: any) => q.eq("tokenHash", tokenHash))
.unique()
if (!token) {
throw new ConvexError("Token de máquina inválido")
}
if (token.revoked) {
throw new ConvexError("Token de máquina revogado")
}
if (token.expiresAt < Date.now()) {
throw new ConvexError("Token de máquina expirado")
}
const machine = await ctx.db.get(token.machineId)
if (!machine) {
throw new ConvexError("Máquina não encontrada para o token fornecido")
}
return { token, machine }
}
function mergeMetadata(current: unknown, patch: Record<string, unknown>) {
if (!current || typeof current !== "object") return patch
return { ...(current as Record<string, unknown>), ...patch }
}
export const register = mutation({
args: {
provisioningSecret: v.string(),
tenantId: v.optional(v.string()),
companySlug: v.optional(v.string()),
hostname: v.string(),
os: v.object({
name: v.string(),
version: v.optional(v.string()),
architecture: v.optional(v.string()),
}),
macAddresses: v.array(v.string()),
serialNumbers: v.array(v.string()),
metadata: v.optional(v.any()),
registeredBy: v.optional(v.string()),
},
handler: async (ctx, args) => {
const secret = getProvisioningSecret()
if (args.provisioningSecret !== secret) {
throw new ConvexError("Código de provisionamento inválido")
}
const tenantId = args.tenantId ?? DEFAULT_TENANT_ID
const identifiers = normalizeIdentifiers(args.macAddresses, args.serialNumbers)
const fingerprint = computeFingerprint(tenantId, args.companySlug, args.hostname, identifiers)
const { companyId, companySlug } = await ensureCompany(ctx, tenantId, args.companySlug)
const now = Date.now()
const existing = await ctx.db
.query("machines")
.withIndex("by_tenant_fingerprint", (q) => q.eq("tenantId", tenantId).eq("fingerprint", fingerprint))
.first()
let machineId: Id<"machines">
if (existing) {
await ctx.db.patch(existing._id, {
tenantId,
companyId: companyId ?? existing.companyId,
companySlug: companySlug ?? existing.companySlug,
hostname: args.hostname,
osName: args.os.name,
osVersion: args.os.version,
architecture: args.os.architecture,
macAddresses: identifiers.macs,
serialNumbers: identifiers.serials,
metadata: args.metadata ? mergeMetadata(existing.metadata, { inventory: args.metadata }) : existing.metadata,
lastHeartbeatAt: now,
updatedAt: now,
status: "online",
registeredBy: args.registeredBy ?? existing.registeredBy,
})
machineId = existing._id
} else {
machineId = await ctx.db.insert("machines", {
tenantId,
companyId,
companySlug,
hostname: args.hostname,
osName: args.os.name,
osVersion: args.os.version,
architecture: args.os.architecture,
macAddresses: identifiers.macs,
serialNumbers: identifiers.serials,
fingerprint,
metadata: args.metadata ? { inventory: args.metadata } : undefined,
lastHeartbeatAt: now,
status: "online",
createdAt: now,
updatedAt: now,
registeredBy: args.registeredBy,
})
}
const previousTokens = await ctx.db
.query("machineTokens")
.withIndex("by_machine", (q) => q.eq("machineId", machineId))
.collect()
for (const token of previousTokens) {
if (!token.revoked) {
await ctx.db.patch(token._id, { revoked: true, lastUsedAt: now })
}
}
const tokenPlain = toHex(randomBytes(32))
const tokenHash = hashToken(tokenPlain)
const expiresAt = now + getTokenTtlMs()
await ctx.db.insert("machineTokens", {
tenantId,
machineId,
tokenHash,
expiresAt,
revoked: false,
createdAt: now,
usageCount: 0,
type: "machine",
})
return {
machineId,
tenantId,
companyId,
companySlug,
machineToken: tokenPlain,
expiresAt,
}
},
})
export const upsertInventory = mutation({
args: {
provisioningSecret: v.string(),
tenantId: v.optional(v.string()),
companySlug: v.optional(v.string()),
hostname: v.string(),
os: v.object({
name: v.string(),
version: v.optional(v.string()),
architecture: v.optional(v.string()),
}),
macAddresses: v.array(v.string()),
serialNumbers: v.array(v.string()),
inventory: v.optional(v.any()),
metrics: v.optional(v.any()),
registeredBy: v.optional(v.string()),
},
handler: async (ctx, args) => {
const secret = getProvisioningSecret()
if (args.provisioningSecret !== secret) {
throw new ConvexError("Código de provisionamento inválido")
}
const tenantId = args.tenantId ?? DEFAULT_TENANT_ID
const identifiers = normalizeIdentifiers(args.macAddresses, args.serialNumbers)
const fingerprint = computeFingerprint(tenantId, args.companySlug, args.hostname, identifiers)
const { companyId, companySlug } = await ensureCompany(ctx, tenantId, args.companySlug)
const now = Date.now()
const metadataPatch = mergeMetadata({}, {
...(args.inventory ? { inventory: args.inventory } : {}),
...(args.metrics ? { metrics: args.metrics } : {}),
})
const existing = await ctx.db
.query("machines")
.withIndex("by_tenant_fingerprint", (q) => q.eq("tenantId", tenantId).eq("fingerprint", fingerprint))
.first()
let machineId: Id<"machines">
if (existing) {
await ctx.db.patch(existing._id, {
tenantId,
companyId: companyId ?? existing.companyId,
companySlug: companySlug ?? existing.companySlug,
hostname: args.hostname,
osName: args.os.name,
osVersion: args.os.version,
architecture: args.os.architecture,
macAddresses: identifiers.macs,
serialNumbers: identifiers.serials,
metadata: mergeMetadata(existing.metadata, metadataPatch),
lastHeartbeatAt: now,
updatedAt: now,
status: args.metrics ? "online" : existing.status ?? "unknown",
registeredBy: args.registeredBy ?? existing.registeredBy,
})
machineId = existing._id
} else {
machineId = await ctx.db.insert("machines", {
tenantId,
companyId,
companySlug,
hostname: args.hostname,
osName: args.os.name,
osVersion: args.os.version,
architecture: args.os.architecture,
macAddresses: identifiers.macs,
serialNumbers: identifiers.serials,
fingerprint,
metadata: metadataPatch,
lastHeartbeatAt: now,
status: args.metrics ? "online" : "unknown",
createdAt: now,
updatedAt: now,
registeredBy: args.registeredBy,
})
}
return {
machineId,
tenantId,
companyId,
companySlug,
status: args.metrics ? "online" : "unknown",
}
},
})
export const heartbeat = mutation({
args: {
machineToken: v.string(),
status: v.optional(v.string()),
hostname: v.optional(v.string()),
os: v.optional(
v.object({
name: v.string(),
version: v.optional(v.string()),
architecture: v.optional(v.string()),
})
),
metrics: v.optional(v.any()),
inventory: v.optional(v.any()),
metadata: v.optional(v.any()),
},
handler: async (ctx, args) => {
const { machine, token } = await getActiveToken(ctx, args.machineToken)
const now = Date.now()
const mergedMetadata = mergeMetadata(machine.metadata, {
...(args.metadata ?? {}),
...(args.metrics ? { metrics: args.metrics } : {}),
...(args.inventory ? { inventory: args.inventory } : {}),
})
await ctx.db.patch(machine._id, {
hostname: args.hostname ?? machine.hostname,
osName: args.os?.name ?? machine.osName,
osVersion: args.os?.version ?? machine.osVersion,
architecture: args.os?.architecture ?? machine.architecture,
lastHeartbeatAt: now,
updatedAt: now,
status: args.status ?? "online",
metadata: mergedMetadata,
})
await ctx.db.patch(token._id, {
lastUsedAt: now,
usageCount: (token.usageCount ?? 0) + 1,
expiresAt: now + getTokenTtlMs(),
})
return {
ok: true,
machineId: machine._id,
expiresAt: now + getTokenTtlMs(),
}
},
})
export const resolveToken = mutation({
args: {
machineToken: v.string(),
},
handler: async (ctx, args) => {
const { machine, token } = await getActiveToken(ctx, args.machineToken)
const now = Date.now()
await ctx.db.patch(token._id, {
lastUsedAt: now,
usageCount: (token.usageCount ?? 0) + 1,
})
return {
machine: {
_id: machine._id,
tenantId: machine.tenantId,
companyId: machine.companyId,
companySlug: machine.companySlug,
hostname: machine.hostname,
osName: machine.osName,
osVersion: machine.osVersion,
architecture: machine.architecture,
authUserId: machine.authUserId,
authEmail: machine.authEmail,
status: machine.status,
lastHeartbeatAt: machine.lastHeartbeatAt,
metadata: machine.metadata,
},
token: {
expiresAt: token.expiresAt,
lastUsedAt: token.lastUsedAt ?? null,
usageCount: token.usageCount ?? 0,
},
}
},
})
export const listByTenant = query({
args: {
tenantId: v.optional(v.string()),
includeMetadata: v.optional(v.boolean()),
},
handler: async (ctx, args) => {
const tenantId = args.tenantId ?? DEFAULT_TENANT_ID
const includeMetadata = Boolean(args.includeMetadata)
const now = Date.now()
const machines = await ctx.db
.query("machines")
.withIndex("by_tenant", (q) => q.eq("tenantId", tenantId))
.collect()
return Promise.all(
machines.map(async (machine) => {
const tokens = await ctx.db
.query("machineTokens")
.withIndex("by_machine", (q) => q.eq("machineId", machine._id))
.collect()
const activeToken = tokens.find((token) => !token.revoked && token.expiresAt > now) ?? null
const derivedStatus =
machine.status ??
(machine.lastHeartbeatAt && now - machine.lastHeartbeatAt <= 5 * 60 * 1000 ? "online" : machine.lastHeartbeatAt ? "offline" : "unknown")
const metadata = includeMetadata ? (machine.metadata ?? null) : null
let metrics: Record<string, unknown> | null = null
let inventory: Record<string, unknown> | null = null
if (metadata && typeof metadata === "object") {
const metaRecord = metadata as Record<string, unknown>
if (metaRecord.metrics && typeof metaRecord.metrics === "object") {
metrics = metaRecord.metrics as Record<string, unknown>
}
if (metaRecord.inventory && typeof metaRecord.inventory === "object") {
inventory = metaRecord.inventory as Record<string, unknown>
}
}
return {
id: machine._id,
tenantId: machine.tenantId,
hostname: machine.hostname,
companyId: machine.companyId ?? null,
companySlug: machine.companySlug ?? null,
osName: machine.osName,
osVersion: machine.osVersion ?? null,
architecture: machine.architecture ?? null,
macAddresses: machine.macAddresses,
serialNumbers: machine.serialNumbers,
authUserId: machine.authUserId ?? null,
authEmail: machine.authEmail ?? null,
status: derivedStatus,
lastHeartbeatAt: machine.lastHeartbeatAt ?? null,
heartbeatAgeMs: machine.lastHeartbeatAt ? now - machine.lastHeartbeatAt : null,
registeredBy: machine.registeredBy ?? null,
createdAt: machine.createdAt,
updatedAt: machine.updatedAt,
token: activeToken
? {
expiresAt: activeToken.expiresAt,
lastUsedAt: activeToken.lastUsedAt ?? null,
usageCount: activeToken.usageCount ?? 0,
}
: null,
metrics,
inventory,
}
})
)
},
})
export const linkAuthAccount = mutation({
args: {
machineId: v.id("machines"),
authUserId: v.string(),
authEmail: v.string(),
},
handler: async (ctx, args) => {
const machine = await ctx.db.get(args.machineId)
if (!machine) {
throw new ConvexError("Máquina não encontrada")
}
await ctx.db.patch(machine._id, {
authUserId: args.authUserId,
authEmail: args.authEmail,
updatedAt: Date.now(),
})
return { ok: true }
},
})

View file

@ -238,4 +238,43 @@ export default defineSchema({
.index("by_tenant", ["tenantId"]) .index("by_tenant", ["tenantId"])
.index("by_token", ["tenantId", "token"]) .index("by_token", ["tenantId", "token"])
.index("by_invite", ["tenantId", "inviteId"]), .index("by_invite", ["tenantId", "inviteId"]),
machines: defineTable({
tenantId: v.string(),
companyId: v.optional(v.id("companies")),
companySlug: v.optional(v.string()),
authUserId: v.optional(v.string()),
authEmail: v.optional(v.string()),
hostname: v.string(),
osName: v.string(),
osVersion: v.optional(v.string()),
architecture: v.optional(v.string()),
macAddresses: v.array(v.string()),
serialNumbers: v.array(v.string()),
fingerprint: v.string(),
metadata: v.optional(v.any()),
lastHeartbeatAt: v.optional(v.number()),
status: v.optional(v.string()),
createdAt: v.number(),
updatedAt: v.number(),
registeredBy: v.optional(v.string()),
})
.index("by_tenant", ["tenantId"])
.index("by_tenant_company", ["tenantId", "companyId"])
.index("by_tenant_fingerprint", ["tenantId", "fingerprint"]),
machineTokens: defineTable({
tenantId: v.string(),
machineId: v.id("machines"),
tokenHash: v.string(),
expiresAt: v.number(),
revoked: v.boolean(),
createdAt: v.number(),
lastUsedAt: v.optional(v.number()),
usageCount: v.optional(v.number()),
type: v.optional(v.string()),
})
.index("by_token_hash", ["tokenHash"])
.index("by_machine", ["machineId"])
.index("by_tenant_machine", ["tenantId", "machineId"]),
}); });

View file

@ -0,0 +1,74 @@
# Plano Integrado App Desktop & Inventário por Máquina
> Documento vivo. Atualize após cada marco relevante.
## Contexto
- **Objetivo:** Expandir o Sistema de Chamados (Next.js + Convex + Better Auth) para suportar:
- Cliente desktop nativo (Tauri) mantendo UI web e realtime.
- Autenticação máquina-a-máquina usando tokens derivados do inventário.
- Integração com agente de inventário (osquery/FleetDM) para registrar hardware, software e heartbeats.
- Pipeline de distribuição para Windows/macOS/Linux.
- **Escopo inicial:** Focar no fluxo mínimo viável com inventário básico (hostname, OS, identificadores, carga resumida). Métricas avançadas e distribuição automatizada ficam para iteração seguinte.
## Estado Geral
- Web atual permanece operacional com login por usuário/senha.
- Novas features serão adições compatíveis (machine login opcional).
- Melhor abordagem para inventário: usar **osquery + FleetDM** (stack pronta) integrando registros no Convex.
## Marcos & Progresso
| Macro-entrega | Status | Observações |
| --- | --- | --- |
| Documento de arquitetura e roadmap | 🔄 Em andamento | Estrutura criada, aguardando detalhamento incremental a cada etapa. |
| Projeto Tauri inicial apontando para UI Next | 🔄 Em andamento | Estrutura `apps/desktop` criada; pendente testar build após instalar toolchain Rust. |
| Schema Convex + tokens de máquina | ✅ Concluído | Tabelas `machines` / `machineTokens` criadas com TTL e fingerprint. |
| API de registro/heartbeat e exchange Better Auth | 🔄 Em andamento | Endpoints `/api/machines/*` disponíveis; falta testar fluxo end-to-end com app desktop. |
| Integração FleetDM → Convex (inventário básico) | 🔄 Em andamento | Endpoint `/api/integrations/fleet/hosts` criado; falta validar payload real e ajustes de métricas/empresa. |
| Admin > Máquinas (listagem, detalhes, métricas) | ✅ Concluído | Página `/admin/machines` exibe parque completo com status ao vivo, inventário e métricas. |
| Ajustes na UI/Next para sessão por máquina | ⏳ A fazer | Detectar token e exibir info da máquina em tickets. |
| Pipeline de build/distribuição Tauri | ⏳ A fazer | Definir estratégia CI/CD + auto-update. |
| Guia operacional (instalação, uso, suporte) | ⏳ A fazer | Gerar instruções finais com casos de uso. |
Legenda: ✅ concluído · 🔄 em andamento · ⏳ a fazer.
## Dependências Técnicas
- **Tauri Desktop:** Rust + toolchain específico por SO, libwebkit2gtk (Linux), WebView2 (Windows), Xcode (macOS).
- **FleetDM/osquery:** Servidor Fleet (Docker ou VM), enrollment secret por tenant, agentes osquery instalados.
- **Better Auth:** Mechanismo para criar sessões usando subject `machine:*` com escopos restritos.
- **Convex:** Novas tabelas `machines` e `machineTokens`, mutações para registro/heartbeat/exchange.
- **Infra extra:** Endpoints públicos para updater do Tauri, armazenamento de inventário seguro, certificados para assinatura de builds.
## Próximos Passos Imediatos
1. Instalar toolchain Tauri local (Rust + dependências nativas) e testar `pnpm --filter appsdesktop tauri dev` apontando para o Next (`pnpm dev`).
2. Detalhar fluxo de provisioning de máquina no Convex e atualizar este documento.
## Notas de Implementação (Atual)
- Criada pasta `apps/desktop` via `create-tauri-app` com template `vanilla-ts`.
- `src/main.ts` redireciona a WebView para `VITE_APP_URL` (padrão `http://localhost:3000`), reaproveitando a UI Next web.
- `index.html` exibe fallback simples enquanto o Next inicializa.
- Necessário criar `.env` em `apps/desktop` (ou usar variáveis de ambiente) com `VITE_APP_URL` correspondente ao ambiente.
- Novas tabelas Convex: `machines` (fingerprint, heartbeat, vínculo com AuthUser) e `machineTokens` (hash + TTL).
- Novos endpoints Next:
- `POST /api/machines/register` — provisiona máquina, gera token e usuário Better Auth (role `machine`).
- `POST /api/machines/heartbeat` — atualiza estado, métricas e renova TTL.
- `POST /api/machines/sessions` — troca `machineToken` por sessão Better Auth e devolve cookies.
- Webhook FleetDM: `POST /api/integrations/fleet/hosts` (header `x-fleet-secret`) sincroniza inventário/métricas utilizando `machines.upsertInventory`.
- Script `ensureMachineAccount` garante usuário `AuthUser` e senha sincronizada com o token atual.
- Variáveis `.env` novas: `MACHINE_PROVISIONING_SECRET` (obrigatória) e `MACHINE_TOKEN_TTL_MS` (opcional, padrão 30 dias).
- Variável adicional `FLEET_SYNC_SECRET` (opcional) para autenticar webhook do Fleet; se ausente, reutiliza `MACHINE_PROVISIONING_SECRET`.
- Dashboard administrativo: `/admin/machines` usa `AdminMachinesOverview` com dados em tempo real (status, heartbeat, token, inventário enviado pelo agente/Fleet).
### Checklist de dependências Tauri (Linux)
```bash
sudo apt update
sudo apt install libwebkit2gtk-4.1-dev build-essential curl wget file \
libxdo-dev libssl-dev libayatana-appindicator3-dev librsvg2-dev
curl --proto '=https' --tlsv1.2 https://sh.rustup.rs -sSf | sh
# reinicie o terminal e confirme: rustc --version
```
> Ajuste conforme seu sistema operacional (ver https://tauri.app/start/prerequisites/).
---
> Histórico de atualizações:
> - 2025-02-14 — Documento criado com visão geral e plano macro (assistente).

View file

@ -19,6 +19,7 @@
"@dnd-kit/sortable": "^10.0.0", "@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2", "@dnd-kit/utilities": "^3.2.2",
"@hookform/resolvers": "^3.10.0", "@hookform/resolvers": "^3.10.0",
"@noble/hashes": "^1.5.0",
"@paper-design/shaders-react": "^0.0.55", "@paper-design/shaders-react": "^0.0.55",
"@prisma/client": "^6.16.2", "@prisma/client": "^6.16.2",
"@radix-ui/react-avatar": "^1.1.10", "@radix-ui/react-avatar": "^1.1.10",
@ -67,6 +68,8 @@
"devDependencies": { "devDependencies": {
"@eslint/eslintrc": "^3", "@eslint/eslintrc": "^3",
"@tailwindcss/postcss": "^4", "@tailwindcss/postcss": "^4",
"@tauri-apps/api": "^2.8.0",
"@tauri-apps/cli": "^2.8.4",
"@types/node": "^20", "@types/node": "^20",
"@types/pdfkit": "^0.17.3", "@types/pdfkit": "^0.17.3",
"@types/react": "^19", "@types/react": "^19",

138
pnpm-lock.yaml generated
View file

@ -23,6 +23,9 @@ importers:
'@hookform/resolvers': '@hookform/resolvers':
specifier: ^3.10.0 specifier: ^3.10.0
version: 3.10.0(react-hook-form@7.64.0(react@19.2.0)) version: 3.10.0(react-hook-form@7.64.0(react@19.2.0))
'@noble/hashes':
specifier: ^1.5.0
version: 1.8.0
'@paper-design/shaders-react': '@paper-design/shaders-react':
specifier: ^0.0.55 specifier: ^0.0.55
version: 0.0.55(@types/react@19.2.0)(react@19.2.0) version: 0.0.55(@types/react@19.2.0)(react@19.2.0)
@ -162,6 +165,12 @@ importers:
'@tailwindcss/postcss': '@tailwindcss/postcss':
specifier: ^4 specifier: ^4
version: 4.1.14 version: 4.1.14
'@tauri-apps/api':
specifier: ^2.8.0
version: 2.8.0
'@tauri-apps/cli':
specifier: ^2.8.4
version: 2.8.4
'@types/node': '@types/node':
specifier: ^20 specifier: ^20
version: 20.19.19 version: 20.19.19
@ -836,6 +845,10 @@ packages:
resolution: {integrity: sha512-xHK3XHPUW8DTAobU+G0XT+/w+JLM7/8k1UFdB5xg/zTFPnFCobhftzw8wl4Lw2aq/Rvir5pxfZV5fEazmeCJ2g==} resolution: {integrity: sha512-xHK3XHPUW8DTAobU+G0XT+/w+JLM7/8k1UFdB5xg/zTFPnFCobhftzw8wl4Lw2aq/Rvir5pxfZV5fEazmeCJ2g==}
engines: {node: '>= 20.19.0'} engines: {node: '>= 20.19.0'}
'@noble/hashes@1.8.0':
resolution: {integrity: sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==}
engines: {node: ^14.21.3 || >=16}
'@noble/hashes@2.0.1': '@noble/hashes@2.0.1':
resolution: {integrity: sha512-XlOlEbQcE9fmuXxrVTXCTlG2nlRXa9Rj3rr5Ue/+tX+nmkgbX720YHh0VR3hBF9xDvwnb8D2shVGOwNx+ulArw==} resolution: {integrity: sha512-XlOlEbQcE9fmuXxrVTXCTlG2nlRXa9Rj3rr5Ue/+tX+nmkgbX720YHh0VR3hBF9xDvwnb8D2shVGOwNx+ulArw==}
engines: {node: '>= 20.19.0'} engines: {node: '>= 20.19.0'}
@ -1641,6 +1654,80 @@ packages:
resolution: {integrity: sha512-ldZXEhOBb8Is7xLs01fR3YEc3DERiz5silj8tnGkFZytt1abEvl/GhUmCE0PMLaMPTa3Jk4HbKmRlHmu+gCftg==} resolution: {integrity: sha512-ldZXEhOBb8Is7xLs01fR3YEc3DERiz5silj8tnGkFZytt1abEvl/GhUmCE0PMLaMPTa3Jk4HbKmRlHmu+gCftg==}
engines: {node: '>=12'} engines: {node: '>=12'}
'@tauri-apps/api@2.8.0':
resolution: {integrity: sha512-ga7zdhbS2GXOMTIZRT0mYjKJtR9fivsXzsyq5U3vjDL0s6DTMwYRm0UHNjzTY5dh4+LSC68Sm/7WEiimbQNYlw==}
'@tauri-apps/cli-darwin-arm64@2.8.4':
resolution: {integrity: sha512-BKu8HRkYV01SMTa7r4fLx+wjgtRK8Vep7lmBdHDioP6b8XH3q2KgsAyPWfEZaZIkZ2LY4SqqGARaE9oilNe0oA==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [darwin]
'@tauri-apps/cli-darwin-x64@2.8.4':
resolution: {integrity: sha512-imb9PfSd/7G6VAO7v1bQ2A3ZH4NOCbhGJFLchxzepGcXf9NKkfun157JH9mko29K6sqAwuJ88qtzbKCbWJTH9g==}
engines: {node: '>= 10'}
cpu: [x64]
os: [darwin]
'@tauri-apps/cli-linux-arm-gnueabihf@2.8.4':
resolution: {integrity: sha512-Ml215UnDdl7/fpOrF1CNovym/KjtUbCuPgrcZ4IhqUCnhZdXuphud/JT3E8X97Y03TZ40Sjz8raXYI2ET0exzw==}
engines: {node: '>= 10'}
cpu: [arm]
os: [linux]
'@tauri-apps/cli-linux-arm64-gnu@2.8.4':
resolution: {integrity: sha512-pbcgBpMyI90C83CxE5REZ9ODyIlmmAPkkJXtV398X3SgZEIYy5TACYqlyyv2z5yKgD8F8WH4/2fek7+jH+ZXAw==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
'@tauri-apps/cli-linux-arm64-musl@2.8.4':
resolution: {integrity: sha512-zumFeaU1Ws5Ay872FTyIm7z8kfzEHu8NcIn8M6TxbJs0a7GRV21KBdpW1zNj2qy7HynnpQCqjAYXTUUmm9JAOw==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
'@tauri-apps/cli-linux-riscv64-gnu@2.8.4':
resolution: {integrity: sha512-qiqbB3Zz6IyO201f+1ojxLj65WYj8mixL5cOMo63nlg8CIzsP23cPYUrx1YaDPsCLszKZo7tVs14pc7BWf+/aQ==}
engines: {node: '>= 10'}
cpu: [riscv64]
os: [linux]
'@tauri-apps/cli-linux-x64-gnu@2.8.4':
resolution: {integrity: sha512-TaqaDd9Oy6k45Hotx3pOf+pkbsxLaApv4rGd9mLuRM1k6YS/aw81YrsMryYPThrxrScEIUcmNIHaHsLiU4GMkw==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
'@tauri-apps/cli-linux-x64-musl@2.8.4':
resolution: {integrity: sha512-ot9STAwyezN8w+bBHZ+bqSQIJ0qPZFlz/AyscpGqB/JnJQVDFQcRDmUPFEaAtt2UUHSWzN3GoTJ5ypqLBp2WQA==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
'@tauri-apps/cli-win32-arm64-msvc@2.8.4':
resolution: {integrity: sha512-+2aJ/g90dhLiOLFSD1PbElXX3SoMdpO7HFPAZB+xot3CWlAZD1tReUFy7xe0L5GAR16ZmrxpIDM9v9gn5xRy/w==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [win32]
'@tauri-apps/cli-win32-ia32-msvc@2.8.4':
resolution: {integrity: sha512-yj7WDxkL1t9Uzr2gufQ1Hl7hrHuFKTNEOyascbc109EoiAqCp0tgZ2IykQqOZmZOHU884UAWI1pVMqBhS/BfhA==}
engines: {node: '>= 10'}
cpu: [ia32]
os: [win32]
'@tauri-apps/cli-win32-x64-msvc@2.8.4':
resolution: {integrity: sha512-XuvGB4ehBdd7QhMZ9qbj/8icGEatDuBNxyYHbLKsTYh90ggUlPa/AtaqcC1Fo69lGkTmq9BOKrs1aWSi7xDonA==}
engines: {node: '>= 10'}
cpu: [x64]
os: [win32]
'@tauri-apps/cli@2.8.4':
resolution: {integrity: sha512-ejUZBzuQRcjFV+v/gdj/DcbyX/6T4unZQjMSBZwLzP/CymEjKcc2+Fc8xTORThebHDUvqoXMdsCZt8r+hyN15g==}
engines: {node: '>= 10'}
hasBin: true
'@tiptap/core@3.6.5': '@tiptap/core@3.6.5':
resolution: {integrity: sha512-CgXuhevQbBcPfxaXzGZgIY9+aVMSAd68Q21g3EONz1iZBw026QgiaLhGK6jgGTErZL4GoNL/P+gC5nFCvN7+cA==} resolution: {integrity: sha512-CgXuhevQbBcPfxaXzGZgIY9+aVMSAd68Q21g3EONz1iZBw026QgiaLhGK6jgGTErZL4GoNL/P+gC5nFCvN7+cA==}
peerDependencies: peerDependencies:
@ -4491,6 +4578,8 @@ snapshots:
'@noble/ciphers@2.0.1': {} '@noble/ciphers@2.0.1': {}
'@noble/hashes@1.8.0': {}
'@noble/hashes@2.0.1': {} '@noble/hashes@2.0.1': {}
'@nodelib/fs.scandir@2.1.5': '@nodelib/fs.scandir@2.1.5':
@ -5294,6 +5383,55 @@ snapshots:
'@tanstack/table-core@8.21.3': {} '@tanstack/table-core@8.21.3': {}
'@tauri-apps/api@2.8.0': {}
'@tauri-apps/cli-darwin-arm64@2.8.4':
optional: true
'@tauri-apps/cli-darwin-x64@2.8.4':
optional: true
'@tauri-apps/cli-linux-arm-gnueabihf@2.8.4':
optional: true
'@tauri-apps/cli-linux-arm64-gnu@2.8.4':
optional: true
'@tauri-apps/cli-linux-arm64-musl@2.8.4':
optional: true
'@tauri-apps/cli-linux-riscv64-gnu@2.8.4':
optional: true
'@tauri-apps/cli-linux-x64-gnu@2.8.4':
optional: true
'@tauri-apps/cli-linux-x64-musl@2.8.4':
optional: true
'@tauri-apps/cli-win32-arm64-msvc@2.8.4':
optional: true
'@tauri-apps/cli-win32-ia32-msvc@2.8.4':
optional: true
'@tauri-apps/cli-win32-x64-msvc@2.8.4':
optional: true
'@tauri-apps/cli@2.8.4':
optionalDependencies:
'@tauri-apps/cli-darwin-arm64': 2.8.4
'@tauri-apps/cli-darwin-x64': 2.8.4
'@tauri-apps/cli-linux-arm-gnueabihf': 2.8.4
'@tauri-apps/cli-linux-arm64-gnu': 2.8.4
'@tauri-apps/cli-linux-arm64-musl': 2.8.4
'@tauri-apps/cli-linux-riscv64-gnu': 2.8.4
'@tauri-apps/cli-linux-x64-gnu': 2.8.4
'@tauri-apps/cli-linux-x64-musl': 2.8.4
'@tauri-apps/cli-win32-arm64-msvc': 2.8.4
'@tauri-apps/cli-win32-ia32-msvc': 2.8.4
'@tauri-apps/cli-win32-x64-msvc': 2.8.4
'@tiptap/core@3.6.5(@tiptap/pm@3.6.5)': '@tiptap/core@3.6.5(@tiptap/pm@3.6.5)':
dependencies: dependencies:
'@tiptap/pm': 3.6.5 '@tiptap/pm': 3.6.5

View file

@ -0,0 +1,58 @@
-- RedefineTables
PRAGMA defer_foreign_keys=ON;
PRAGMA foreign_keys=OFF;
CREATE TABLE "new_Company" (
"id" TEXT NOT NULL PRIMARY KEY,
"tenantId" TEXT NOT NULL,
"name" TEXT NOT NULL,
"slug" TEXT NOT NULL,
"isAvulso" BOOLEAN NOT NULL DEFAULT false,
"contractedHoursPerMonth" REAL,
"cnpj" TEXT,
"domain" TEXT,
"phone" TEXT,
"description" TEXT,
"address" TEXT,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL
);
INSERT INTO "new_Company" ("address", "cnpj", "createdAt", "description", "domain", "id", "name", "phone", "slug", "tenantId", "updatedAt") SELECT "address", "cnpj", "createdAt", "description", "domain", "id", "name", "phone", "slug", "tenantId", "updatedAt" FROM "Company";
DROP TABLE "Company";
ALTER TABLE "new_Company" RENAME TO "Company";
CREATE INDEX "Company_tenantId_name_idx" ON "Company"("tenantId", "name");
CREATE UNIQUE INDEX "Company_tenantId_slug_key" ON "Company"("tenantId", "slug");
CREATE TABLE "new_Ticket" (
"id" TEXT NOT NULL PRIMARY KEY,
"tenantId" TEXT NOT NULL,
"reference" INTEGER NOT NULL DEFAULT 0,
"subject" TEXT NOT NULL,
"summary" TEXT,
"status" TEXT NOT NULL DEFAULT 'PENDING',
"priority" TEXT NOT NULL DEFAULT 'MEDIUM',
"channel" TEXT NOT NULL DEFAULT 'EMAIL',
"queueId" TEXT,
"requesterId" TEXT NOT NULL,
"assigneeId" TEXT,
"slaPolicyId" TEXT,
"companyId" TEXT,
"dueAt" DATETIME,
"firstResponseAt" DATETIME,
"resolvedAt" DATETIME,
"closedAt" DATETIME,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL,
CONSTRAINT "Ticket_requesterId_fkey" FOREIGN KEY ("requesterId") REFERENCES "User" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
CONSTRAINT "Ticket_assigneeId_fkey" FOREIGN KEY ("assigneeId") REFERENCES "User" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT "Ticket_queueId_fkey" FOREIGN KEY ("queueId") REFERENCES "Queue" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT "Ticket_slaPolicyId_fkey" FOREIGN KEY ("slaPolicyId") REFERENCES "SlaPolicy" ("id") ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT "Ticket_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "Company" ("id") ON DELETE SET NULL ON UPDATE CASCADE
);
INSERT INTO "new_Ticket" ("assigneeId", "channel", "closedAt", "companyId", "createdAt", "dueAt", "firstResponseAt", "id", "priority", "queueId", "reference", "requesterId", "resolvedAt", "slaPolicyId", "status", "subject", "summary", "tenantId", "updatedAt") SELECT "assigneeId", "channel", "closedAt", "companyId", "createdAt", "dueAt", "firstResponseAt", "id", "priority", "queueId", "reference", "requesterId", "resolvedAt", "slaPolicyId", "status", "subject", "summary", "tenantId", "updatedAt" FROM "Ticket";
DROP TABLE "Ticket";
ALTER TABLE "new_Ticket" RENAME TO "Ticket";
CREATE INDEX "Ticket_tenantId_status_idx" ON "Ticket"("tenantId", "status");
CREATE INDEX "Ticket_tenantId_queueId_idx" ON "Ticket"("tenantId", "queueId");
CREATE INDEX "Ticket_tenantId_assigneeId_idx" ON "Ticket"("tenantId", "assigneeId");
CREATE INDEX "Ticket_tenantId_companyId_idx" ON "Ticket"("tenantId", "companyId");
PRAGMA foreign_keys=ON;
PRAGMA defer_foreign_keys=OFF;

View file

@ -0,0 +1,24 @@
import { AppShell } from "@/components/app-shell"
import { SiteHeader } from "@/components/site-header"
import { AdminMachinesOverview } from "@/components/admin/machines/admin-machines-overview"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
export const runtime = "nodejs"
export const dynamic = "force-dynamic"
export default function AdminMachinesPage() {
return (
<AppShell
header={
<SiteHeader
title="Parque de máquinas"
lead="Acompanhe quais dispositivos estão ativos, métricas recentes e a sincronização do agente."
/>
}
>
<div className="mx-auto w-full max-w-6xl px-4 pb-12 lg:px-6">
<AdminMachinesOverview tenantId={DEFAULT_TENANT_ID} />
</div>
</AppShell>
)
}

View file

@ -0,0 +1,184 @@
import { NextResponse } from "next/server"
import { z } from "zod"
import { ConvexHttpClient } from "convex/browser"
import { api } from "@/convex/_generated/api"
import { env } from "@/lib/env"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
const fleetHostSchema = z.object({
host: z
.object({
id: z.number().optional(),
hostname: z.string().optional(),
display_name: z.string().optional(),
platform: z.string().optional(),
os_version: z.string().optional(),
hardware_model: z.string().optional(),
hardware_serial: z.string().optional(),
hardware_uuid: z.string().optional(),
uuid: z.string().optional(),
device_id: z.string().optional(),
primary_ip: z.string().optional(),
public_ip: z.string().optional(),
primary_mac: z.string().optional(),
macs: z.string().optional(),
serial_number: z.string().optional(),
memory: z.number().optional(),
cpu_type: z.string().optional(),
cpu_physical_cores: z.number().optional(),
cpu_logical_cores: z.number().optional(),
hardware_vendor: z.string().optional(),
computer_name: z.string().optional(),
detail_updated_at: z.string().optional(),
platform_like: z.string().optional(),
osquery_version: z.string().optional(),
team_id: z.number().optional(),
software: z
.array(
z.object({
name: z.string().optional(),
version: z.string().optional(),
source: z.string().optional(),
})
)
.optional(),
labels: z
.array(
z.object({
id: z.number(),
name: z.string(),
})
)
.optional(),
})
.transform((value) => value ?? {}),
})
function extractMacs(host: z.infer<typeof fleetHostSchema>["host"]) {
const macs = new Set<string>()
const append = (input?: string | null) => {
if (!input) return
input
.split(/[\s,]+/)
.map((mac) => mac.trim())
.filter(Boolean)
.forEach((mac) => macs.add(mac))
}
append(host.primary_mac)
append(host.macs)
return Array.from(macs)
}
function extractSerials(host: z.infer<typeof fleetHostSchema>["host"]) {
return [
host.hardware_serial,
host.hardware_uuid,
host.uuid,
host.serial_number,
host.device_id,
]
.map((value) => value?.trim())
.filter((value): value is string => Boolean(value))
}
export async function POST(request: Request) {
const fleetSecret = env.FLEET_SYNC_SECRET ?? env.MACHINE_PROVISIONING_SECRET
if (!fleetSecret) {
return NextResponse.json({ error: "Sincronização Fleet não configurada" }, { status: 500 })
}
const providedSecret = request.headers.get("x-fleet-secret") ?? request.headers.get("authorization")?.replace(/^Bearer\s+/i, "")
if (!providedSecret || providedSecret !== fleetSecret) {
return NextResponse.json({ error: "Não autorizado" }, { status: 401 })
}
const convexUrl = env.NEXT_PUBLIC_CONVEX_URL
if (!convexUrl) {
return NextResponse.json({ error: "Convex não configurado" }, { status: 500 })
}
let parsed
try {
const raw = await request.json()
parsed = fleetHostSchema.parse(raw)
} catch (error) {
return NextResponse.json({ error: "Payload inválido", details: error instanceof Error ? error.message : String(error) }, { status: 400 })
}
const host = parsed.host
const hostname = host.hostname ?? host.computer_name ?? host.display_name
if (!hostname) {
return NextResponse.json({ error: "Host sem hostname válido" }, { status: 400 })
}
const macAddresses = extractMacs(host)
const serialNumbers = extractSerials(host)
if (macAddresses.length === 0 && serialNumbers.length === 0) {
return NextResponse.json({ error: "Host sem identificadores de hardware (MAC ou serial)" }, { status: 400 })
}
const osInfo = {
name: host.os_version ?? host.platform ?? "desconhecido",
version: host.os_version,
architecture: host.platform_like,
}
const inventory = {
fleet: {
id: host.id,
teamId: host.team_id,
detailUpdatedAt: host.detail_updated_at,
osqueryVersion: host.osquery_version,
},
hardware: {
vendor: host.hardware_vendor,
model: host.hardware_model,
serial: host.hardware_serial ?? host.serial_number,
cpuType: host.cpu_type,
physicalCores: host.cpu_physical_cores,
logicalCores: host.cpu_logical_cores,
memoryBytes: host.memory,
},
network: {
primaryIp: host.primary_ip,
publicIp: host.public_ip,
macAddresses,
},
labels: host.labels,
software: host.software?.slice(0, 50).map((item) => ({
name: item.name,
version: item.version,
source: item.source,
})),
}
const metrics = {
memoryBytes: host.memory,
cpuPhysicalCores: host.cpu_physical_cores,
cpuLogicalCores: host.cpu_logical_cores,
}
const client = new ConvexHttpClient(convexUrl)
try {
const result = await client.mutation(api.machines.upsertInventory, {
provisioningSecret: fleetSecret,
tenantId: DEFAULT_TENANT_ID,
hostname,
companySlug: undefined,
os: osInfo,
macAddresses,
serialNumbers,
inventory,
metrics,
registeredBy: "fleet",
})
return NextResponse.json({ ok: true, machineId: result.machineId, status: result.status })
} catch (error) {
console.error("[fleet.hosts] Falha ao sincronizar inventário", error)
return NextResponse.json({ error: "Falha ao sincronizar inventário" }, { status: 500 })
}
}

View file

@ -0,0 +1,51 @@
import { NextResponse } from "next/server"
import { z } from "zod"
import { ConvexHttpClient } from "convex/browser"
import { api } from "@/convex/_generated/api"
import { env } from "@/lib/env"
const heartbeatSchema = z.object({
machineToken: z.string().min(1),
status: z.string().optional(),
hostname: z.string().optional(),
os: z
.object({
name: z.string(),
version: z.string().optional(),
architecture: z.string().optional(),
})
.optional(),
metrics: z.record(z.string(), z.unknown()).optional(),
inventory: z.record(z.string(), z.unknown()).optional(),
metadata: z.record(z.string(), z.unknown()).optional(),
})
export async function POST(request: Request) {
if (request.method !== "POST") {
return NextResponse.json({ error: "Método não permitido" }, { status: 405 })
}
const convexUrl = env.NEXT_PUBLIC_CONVEX_URL
if (!convexUrl) {
return NextResponse.json({ error: "Convex não configurado" }, { status: 500 })
}
let payload
try {
const raw = await request.json()
payload = heartbeatSchema.parse(raw)
} catch (error) {
return NextResponse.json({ error: "Payload inválido", details: error instanceof Error ? error.message : String(error) }, { status: 400 })
}
const client = new ConvexHttpClient(convexUrl)
try {
const response = await client.mutation(api.machines.heartbeat, payload)
return NextResponse.json(response)
} catch (error) {
console.error("[machines.heartbeat] Falha ao registrar heartbeat", error)
return NextResponse.json({ error: "Falha ao registrar heartbeat" }, { status: 500 })
}
}

View file

@ -0,0 +1,94 @@
import { NextResponse } from "next/server"
import { z } from "zod"
import { ConvexHttpClient } from "convex/browser"
import { api } from "@/convex/_generated/api"
import type { Id } from "@/convex/_generated/dataModel"
import { env } from "@/lib/env"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { ensureMachineAccount } from "@/server/machines-auth"
const registerSchema = z
.object({
provisioningSecret: z.string().min(1),
tenantId: z.string().optional(),
companySlug: z.string().optional(),
hostname: z.string().min(1),
os: z.object({
name: z.string().min(1),
version: z.string().optional(),
architecture: z.string().optional(),
}),
macAddresses: z.array(z.string()).default([]),
serialNumbers: z.array(z.string()).default([]),
metadata: z.record(z.string(), z.unknown()).optional(),
registeredBy: z.string().optional(),
})
.refine(
(data) => (data.macAddresses && data.macAddresses.length > 0) || (data.serialNumbers && data.serialNumbers.length > 0),
{ message: "Informe ao menos um MAC address ou número de série" }
)
export async function POST(request: Request) {
if (request.method !== "POST") {
return NextResponse.json({ error: "Método não permitido" }, { status: 405 })
}
const convexUrl = env.NEXT_PUBLIC_CONVEX_URL
if (!convexUrl) {
return NextResponse.json({ error: "Convex não configurado" }, { status: 500 })
}
let payload
try {
const raw = await request.json()
payload = registerSchema.parse(raw)
} catch (error) {
return NextResponse.json({ error: "Payload inválido", details: error instanceof Error ? error.message : String(error) }, { status: 400 })
}
const client = new ConvexHttpClient(convexUrl)
try {
const registration = await client.mutation(api.machines.register, {
provisioningSecret: payload.provisioningSecret,
tenantId: payload.tenantId ?? DEFAULT_TENANT_ID,
companySlug: payload.companySlug ?? undefined,
hostname: payload.hostname,
os: payload.os,
macAddresses: payload.macAddresses,
serialNumbers: payload.serialNumbers,
metadata: payload.metadata,
registeredBy: payload.registeredBy,
})
const account = await ensureMachineAccount({
machineId: registration.machineId,
tenantId: registration.tenantId ?? DEFAULT_TENANT_ID,
hostname: payload.hostname,
machineToken: registration.machineToken,
})
await client.mutation(api.machines.linkAuthAccount, {
machineId: registration.machineId as Id<"machines">,
authUserId: account.authUserId,
authEmail: account.authEmail,
})
return NextResponse.json(
{
machineId: registration.machineId,
tenantId: registration.tenantId,
companyId: registration.companyId,
companySlug: registration.companySlug,
machineToken: registration.machineToken,
machineEmail: account.authEmail,
expiresAt: registration.expiresAt,
},
{ status: 201 }
)
} catch (error) {
console.error("[machines.register] Falha no provisionamento", error)
return NextResponse.json({ error: "Falha ao provisionar máquina" }, { status: 500 })
}
}

View file

@ -0,0 +1,96 @@
import { NextResponse } from "next/server"
import { z } from "zod"
import { ConvexHttpClient } from "convex/browser"
import { api } from "@/convex/_generated/api"
import type { Id } from "@/convex/_generated/dataModel"
import { env } from "@/lib/env"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { ensureMachineAccount } from "@/server/machines-auth"
import { auth } from "@/lib/auth"
const sessionSchema = z.object({
machineToken: z.string().min(1),
rememberMe: z.boolean().optional(),
})
export async function POST(request: Request) {
if (request.method !== "POST") {
return NextResponse.json({ error: "Método não permitido" }, { status: 405 })
}
const convexUrl = env.NEXT_PUBLIC_CONVEX_URL
if (!convexUrl) {
return NextResponse.json({ error: "Convex não configurado" }, { status: 500 })
}
let payload
try {
const raw = await request.json()
payload = sessionSchema.parse(raw)
} catch (error) {
return NextResponse.json({ error: "Payload inválido", details: error instanceof Error ? error.message : String(error) }, { status: 400 })
}
const client = new ConvexHttpClient(convexUrl)
try {
const resolved = await client.mutation(api.machines.resolveToken, { machineToken: payload.machineToken })
let machineEmail = resolved.machine.authEmail ?? null
if (!machineEmail) {
const account = await ensureMachineAccount({
machineId: resolved.machine._id,
tenantId: resolved.machine.tenantId ?? DEFAULT_TENANT_ID,
hostname: resolved.machine.hostname,
machineToken: payload.machineToken,
})
await client.mutation(api.machines.linkAuthAccount, {
machineId: resolved.machine._id as Id<"machines">,
authUserId: account.authUserId,
authEmail: account.authEmail,
})
machineEmail = account.authEmail
}
const signIn = await auth.api.signInEmail({
body: {
email: machineEmail,
password: payload.machineToken,
rememberMe: payload.rememberMe ?? true,
},
returnHeaders: true,
})
const response = NextResponse.json(
{
ok: true,
machine: {
id: resolved.machine._id,
hostname: resolved.machine.hostname,
osName: resolved.machine.osName,
osVersion: resolved.machine.osVersion,
architecture: resolved.machine.architecture,
status: resolved.machine.status,
lastHeartbeatAt: resolved.machine.lastHeartbeatAt,
companyId: resolved.machine.companyId,
companySlug: resolved.machine.companySlug,
metadata: resolved.machine.metadata,
},
session: signIn.response,
},
{ status: 200 }
)
signIn.headers.forEach((value, key) => {
response.headers.set(key, value)
})
return response
} catch (error) {
console.error("[machines.sessions] Falha ao criar sessão", error)
return NextResponse.json({ error: "Falha ao autenticar máquina" }, { status: 500 })
}
}

View file

@ -0,0 +1,543 @@
"use client"
import { useEffect, useMemo, useState } from "react"
import { useQuery } from "convex/react"
import { format, formatDistanceToNowStrict } from "date-fns"
import { ptBR } from "date-fns/locale"
import { toast } from "sonner"
import { ClipboardCopy, ServerCog } from "lucide-react"
import { api } from "@/convex/_generated/api"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import { Separator } from "@/components/ui/separator"
import { cn } from "@/lib/utils"
type MachineMetrics = Record<string, unknown> | null
type MachineLabel = {
id?: number | string
name?: string
}
type MachineSoftware = {
name?: string
version?: string
source?: string
}
type MachineInventory = {
hardware?: {
vendor?: string
model?: string
serial?: string
cpuType?: string
physicalCores?: number
logicalCores?: number
memoryBytes?: number
memory?: number
}
network?: {
primaryIp?: string
publicIp?: string
macAddresses?: string[]
}
software?: MachineSoftware[]
labels?: MachineLabel[]
fleet?: {
id?: number | string
teamId?: number | string
detailUpdatedAt?: string
osqueryVersion?: string
}
}
type MachinesQueryItem = {
id: string
tenantId: string
hostname: string
companyId: string | null
companySlug: string | null
osName: string | null
osVersion: string | null
architecture: string | null
macAddresses: string[]
serialNumbers: string[]
authUserId: string | null
authEmail: string | null
status: string | null
lastHeartbeatAt: number | null
heartbeatAgeMs: number | null
registeredBy: string | null
createdAt: number
updatedAt: number
token: {
expiresAt: number
lastUsedAt: number | null
usageCount: number
} | null
metrics: MachineMetrics
inventory: MachineInventory | null
}
function useMachinesQuery(tenantId: string): MachinesQueryItem[] {
return (
(useQuery(api.machines.listByTenant, {
tenantId,
includeMetadata: true,
}) ?? []) as MachinesQueryItem[]
)
}
const statusLabels: Record<string, string> = {
online: "Online",
offline: "Offline",
maintenance: "Manutenção",
blocked: "Bloqueada",
unknown: "Desconhecida",
}
const statusClasses: Record<string, string> = {
online: "border-emerald-500/20 bg-emerald-500/15 text-emerald-600",
offline: "border-rose-500/20 bg-rose-500/15 text-rose-600",
maintenance: "border-amber-500/20 bg-amber-500/15 text-amber-600",
blocked: "border-orange-500/20 bg-orange-500/15 text-orange-600",
unknown: "border-slate-300 bg-slate-200 text-slate-700",
}
function formatRelativeTime(date?: Date | null) {
if (!date) return "Nunca"
try {
return formatDistanceToNowStrict(date, { addSuffix: true, locale: ptBR })
} catch {
return "—"
}
}
function formatDate(date?: Date | null) {
if (!date) return "—"
return format(date, "dd/MM/yyyy HH:mm")
}
function formatBytes(bytes?: number | null) {
if (!bytes || Number.isNaN(bytes)) return "—"
const units = ["B", "KB", "MB", "GB", "TB"]
let value = bytes
let unitIndex = 0
while (value >= 1024 && unitIndex < units.length - 1) {
value /= 1024
unitIndex += 1
}
return `${value.toFixed(value >= 10 || unitIndex === 0 ? 0 : 1)} ${units[unitIndex]}`
}
function formatPercent(value?: number | null) {
if (value === null || value === undefined || Number.isNaN(value)) return "—"
const normalized = value > 1 ? value : value * 100
return `${normalized.toFixed(0)}%`
}
function getStatusVariant(status?: string | null) {
if (!status) return { label: statusLabels.unknown, className: statusClasses.unknown }
const normalized = status.toLowerCase()
return {
label: statusLabels[normalized] ?? status,
className: statusClasses[normalized] ?? statusClasses.unknown,
}
}
export function AdminMachinesOverview({ tenantId }: { tenantId: string }) {
const machines = useMachinesQuery(tenantId)
const [selectedId, setSelectedId] = useState<string | null>(null)
useEffect(() => {
if (machines.length === 0) {
setSelectedId(null)
return
}
if (!selectedId) {
setSelectedId(machines[0]?.id ?? null)
} else if (!machines.some((machine) => machine.id === selectedId)) {
setSelectedId(machines[0]?.id ?? null)
}
}, [machines, selectedId])
const selectedMachine = useMemo(() => machines.find((item) => item.id === selectedId) ?? null, [machines, selectedId])
return (
<div className="grid gap-6 xl:grid-cols-[minmax(0,1fr)_minmax(0,400px)]">
<Card className="border-slate-200">
<CardHeader>
<CardTitle>Máquinas registradas</CardTitle>
<CardDescription>Sincronizadas via agente local ou Fleet. Atualiza em tempo real.</CardDescription>
</CardHeader>
<CardContent className="overflow-hidden">
{machines.length === 0 ? (
<EmptyState />
) : (
<div className="overflow-x-auto">
<Table>
<TableHeader>
<TableRow>
<TableHead>Hostname</TableHead>
<TableHead>Status</TableHead>
<TableHead>Último heartbeat</TableHead>
<TableHead>Empresa</TableHead>
<TableHead>Plataforma</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{machines.map((machine: MachinesQueryItem) => (
<TableRow
key={machine.id}
onClick={() => setSelectedId(machine.id)}
className={cn(
"cursor-pointer transition-colors hover:bg-muted/50",
selectedId === machine.id ? "bg-muted/60" : undefined
)}
>
<TableCell>
<div className="font-medium">{machine.hostname}</div>
<p className="text-xs text-muted-foreground">{machine.authEmail ?? "—"}</p>
</TableCell>
<TableCell className="space-y-1">
<MachineStatusBadge status={machine.status} />
</TableCell>
<TableCell>
<p className="text-sm text-muted-foreground">
{formatRelativeTime(machine.lastHeartbeatAt ? new Date(machine.lastHeartbeatAt) : null)}
</p>
</TableCell>
<TableCell>
<p className="text-sm font-medium text-muted-foreground">{machine.companySlug ?? "—"}</p>
</TableCell>
<TableCell>
<p className="text-sm font-medium">
{machine.osName ?? "—"}
{machine.osVersion ? ` ${machine.osVersion}` : ""}
</p>
<p className="text-xs text-muted-foreground">
{machine.architecture ? machine.architecture.toUpperCase() : "—"}
</p>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
)}
</CardContent>
</Card>
<MachineDetails machine={selectedMachine ?? null} />
</div>
)
}
function MachineStatusBadge({ status }: { status?: string | null }) {
const { label, className } = getStatusVariant(status)
return <Badge className={cn("border", className)}>{label}</Badge>
}
function EmptyState() {
return (
<div className="flex flex-col items-center gap-3 rounded-lg border border-dashed border-slate-300 bg-slate-50/50 py-12 text-center">
<ServerCog className="size-10 text-slate-400" />
<div className="space-y-1">
<p className="text-sm font-semibold text-slate-600">Nenhuma máquina registrada ainda</p>
<p className="text-sm text-muted-foreground">
Execute o agente local ou o webhook do Fleet para registrar as máquinas do tenant.
</p>
</div>
</div>
)
}
type MachineDetailsProps = {
machine: MachinesQueryItem | null
}
function MachineDetails({ machine }: MachineDetailsProps) {
const metadata = machine?.inventory ?? null
const metrics = machine?.metrics ?? null
const hardware = metadata?.hardware ?? null
const network = metadata?.network ?? null
const software = metadata?.software ?? null
const labels = metadata?.labels ?? null
const fleet = metadata?.fleet ?? null
const lastHeartbeatDate = machine?.lastHeartbeatAt ? new Date(machine.lastHeartbeatAt) : null
const tokenExpiry = machine?.token?.expiresAt ? new Date(machine.token.expiresAt) : null
const tokenLastUsed = machine?.token?.lastUsedAt ? new Date(machine.token.lastUsedAt) : null
const copyEmail = async () => {
if (!machine?.authEmail) return
try {
await navigator.clipboard.writeText(machine.authEmail)
toast.success("E-mail da máquina copiado.")
} catch {
toast.error("Não foi possível copiar o e-mail da máquina.")
}
}
return (
<Card className="border-slate-200">
<CardHeader>
<CardTitle>Detalhes</CardTitle>
<CardDescription>Resumo da máquina selecionada.</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
{!machine ? (
<p className="text-sm text-muted-foreground">Selecione uma máquina para visualizar detalhes.</p>
) : (
<div className="space-y-6">
<section className="space-y-3">
<div className="flex items-start justify-between gap-2">
<div className="space-y-1">
<p className="text-sm font-semibold text-foreground">{machine.hostname}</p>
<p className="text-xs text-muted-foreground">
{machine.authEmail ?? "E-mail não definido"}
</p>
{machine.companySlug ? (
<p className="text-xs text-muted-foreground">
Empresa vinculada: <span className="font-medium text-foreground">{machine.companySlug}</span>
</p>
) : null}
</div>
<MachineStatusBadge status={machine.status} />
</div>
<div className="flex flex-wrap items-center gap-2">
<Badge variant="outline" className="border-slate-300 bg-slate-100 text-xs font-medium text-slate-700">
{machine.osName ?? "SO desconhecido"} {machine.osVersion ?? ""}
</Badge>
<Badge variant="outline" className="border-slate-300 bg-slate-100 text-xs font-medium text-slate-700">
{machine.architecture?.toUpperCase() ?? "Arquitetura indefinida"}
</Badge>
</div>
<div className="flex flex-wrap gap-2">
{machine.authEmail ? (
<Button size="sm" variant="outline" onClick={copyEmail} className="gap-2">
<ClipboardCopy className="size-4" />
Copiar e-mail
</Button>
) : null}
{machine.registeredBy ? (
<Badge variant="outline">Registrada via {machine.registeredBy}</Badge>
) : null}
</div>
</section>
<section className="space-y-2">
<h4 className="text-sm font-semibold">Sincronização</h4>
<div className="grid gap-2 text-sm text-muted-foreground">
<div className="flex justify-between gap-4">
<span>Último heartbeat</span>
<span className="text-right font-medium text-foreground">
{formatRelativeTime(lastHeartbeatDate)}
</span>
</div>
<div className="flex justify-between gap-4">
<span>Criada em</span>
<span className="text-right font-medium text-foreground">{formatDate(new Date(machine.createdAt))}</span>
</div>
<div className="flex justify-between gap-4">
<span>Atualizada em</span>
<span className="text-right font-medium text-foreground">{formatDate(new Date(machine.updatedAt))}</span>
</div>
<div className="flex justify-between gap-4">
<span>Token expira</span>
<span className="text-right font-medium text-foreground">
{tokenExpiry ? formatRelativeTime(tokenExpiry) : "—"}
</span>
</div>
<div className="flex justify-between gap-4">
<span>Token usado por último</span>
<span className="text-right font-medium text-foreground">
{tokenLastUsed ? formatRelativeTime(tokenLastUsed) : "—"}
</span>
</div>
<div className="flex justify-between gap-4">
<span>Uso do token</span>
<span className="text-right font-medium text-foreground">{machine.token?.usageCount ?? 0} trocas</span>
</div>
</div>
</section>
{metrics && typeof metrics === "object" ? (
<section className="space-y-2">
<h4 className="text-sm font-semibold">Métricas recentes</h4>
<MetricsGrid metrics={metrics} />
</section>
) : null}
{hardware || network || (labels && labels.length > 0) ? (
<section className="space-y-3">
<div>
<h4 className="text-sm font-semibold">Inventário</h4>
<p className="text-xs text-muted-foreground">
Dados sincronizados via agente ou Fleet.
</p>
</div>
<div className="space-y-3 text-sm text-muted-foreground">
{hardware ? (
<div className="rounded-md border border-slate-200 bg-slate-50/60 p-3">
<p className="text-xs font-semibold uppercase text-slate-500">Hardware</p>
<div className="mt-2 grid gap-1">
<DetailLine label="Fabricante" value={hardware.vendor} />
<DetailLine label="Modelo" value={hardware.model} />
<DetailLine label="Número de série" value={hardware.serial} />
<DetailLine label="CPU" value={hardware.cpuType} />
<DetailLine
label="Núcleos"
value={`${hardware.physicalCores ?? "?"} físicos / ${hardware.logicalCores ?? "?"} lógicos`}
/>
<DetailLine label="Memória" value={formatBytes(Number(hardware.memoryBytes ?? hardware.memory))} />
</div>
</div>
) : null}
{network ? (
<div className="rounded-md border border-slate-200 bg-slate-50/60 p-3">
<p className="text-xs font-semibold uppercase text-slate-500">Rede</p>
<div className="mt-2 grid gap-1">
<DetailLine label="IP primário" value={network.primaryIp} />
<DetailLine label="IP público" value={network.publicIp} />
<DetailLine
label="MAC addresses"
value={
Array.isArray(network.macAddresses)
? (network.macAddresses as string[]).join(", ")
: machine?.macAddresses.join(", ")
}
/>
</div>
</div>
) : null}
{labels && labels.length > 0 ? (
<div className="rounded-md border border-slate-200 bg-slate-50/60 p-3">
<p className="text-xs font-semibold uppercase text-slate-500">Labels</p>
<div className="mt-2 flex flex-wrap gap-2">
{labels.slice(0, 12).map((label, index) => (
<Badge key={String(label.id ?? `${label.name ?? "label"}-${index}`)} variant="outline">
{label.name ?? `Label ${index + 1}`}
</Badge>
))}
{labels.length > 12 ? (
<Badge variant="outline">+{labels.length - 12} outras</Badge>
) : null}
</div>
</div>
) : null}
</div>
</section>
) : null}
{fleet ? (
<section className="space-y-2 text-sm text-muted-foreground">
<Separator />
<div className="flex items-center justify-between">
<span>ID Fleet</span>
<span className="font-medium text-foreground">{fleet.id ?? "—"}</span>
</div>
<div className="flex items-center justify-between">
<span>Team ID</span>
<span className="font-medium text-foreground">{fleet.teamId ?? "—"}</span>
</div>
<div className="flex items-center justify-between">
<span>Detalhes atualizados</span>
<span className="font-medium text-foreground">
{fleet.detailUpdatedAt ? formatDate(new Date(String(fleet.detailUpdatedAt))) : "—"}
</span>
</div>
<div className="flex items-center justify-between">
<span>Versão osquery</span>
<span className="font-medium text-foreground">{fleet.osqueryVersion ?? "—"}</span>
</div>
</section>
) : null}
{software && software.length > 0 ? (
<section className="space-y-2">
<h4 className="text-sm font-semibold">Softwares detectados</h4>
<div className="rounded-md border border-slate-200 bg-slate-50/60">
<Table>
<TableHeader>
<TableRow className="border-slate-200 bg-slate-100/80">
<TableHead className="text-xs text-slate-500">Nome</TableHead>
<TableHead className="text-xs text-slate-500">Versão</TableHead>
<TableHead className="text-xs text-slate-500">Fonte</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{software.slice(0, 6).map((item, index) => (
<TableRow key={`${item.name ?? "software"}-${index}`} className="border-slate-100">
<TableCell className="text-sm text-foreground">{item.name ?? "—"}</TableCell>
<TableCell className="text-sm text-muted-foreground">{item.version ?? "—"}</TableCell>
<TableCell className="text-sm text-muted-foreground">{item.source ?? "—"}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
{software.length > 6 ? (
<p className="px-3 py-2 text-xs text-muted-foreground">
+{software.length - 6} softwares adicionais sincronizados via Fleet.
</p>
) : null}
</div>
</section>
) : null}
</div>
)}
</CardContent>
</Card>
)
}
function DetailLine({ label, value }: { label: string; value?: string | number | null }) {
if (value === null || value === undefined) return null
if (typeof value === "string" && (value.trim() === "" || value === "undefined" || value === "null")) {
return null
}
return (
<div className="flex items-center justify-between gap-4">
<span>{label}</span>
<span className="text-right font-medium text-foreground">{value}</span>
</div>
)
}
function MetricsGrid({ metrics }: { metrics: MachineMetrics }) {
const data = (metrics ?? {}) as Record<string, unknown>
const cpu = Number(data.cpuUsage ?? data.cpu ?? data.cpu_percent ?? NaN)
const memory = Number(data.memoryBytes ?? data.memory ?? data.memory_used ?? NaN)
const disk = Number(data.diskUsage ?? data.disk ?? NaN)
return (
<div className="grid gap-2 rounded-md border border-slate-200 bg-slate-50/60 p-3 text-sm text-muted-foreground sm:grid-cols-3">
<div>
<p className="text-xs uppercase text-slate-500">CPU</p>
<p className="text-sm font-semibold text-foreground">{formatPercent(cpu)}</p>
</div>
<div>
<p className="text-xs uppercase text-slate-500">Memória</p>
<p className="text-sm font-semibold text-foreground">{formatBytes(memory)}</p>
</div>
<div>
<p className="text-xs uppercase text-slate-500">Disco</p>
<p className="text-sm font-semibold text-foreground">
{Number.isNaN(disk) ? "—" : `${formatPercent(disk)}`}
</p>
</div>
</div>
)
}

View file

@ -11,7 +11,8 @@ import {
PanelsTopLeft, PanelsTopLeft,
Users, Users,
Waypoints, Waypoints,
Timer, Timer,
MonitorCog,
Layers3, Layers3,
UserPlus, UserPlus,
} from "lucide-react" } from "lucide-react"
@ -90,6 +91,7 @@ const navigation: { versions: string[]; navMain: NavigationGroup[] } = {
{ title: "Canais & roteamento", url: "/admin/channels", icon: Waypoints, requiredRole: "admin" }, { title: "Canais & roteamento", url: "/admin/channels", icon: Waypoints, requiredRole: "admin" },
{ title: "Times & papéis", url: "/admin/teams", icon: Users, requiredRole: "admin" }, { title: "Times & papéis", url: "/admin/teams", icon: Users, requiredRole: "admin" },
{ title: "Empresas & clientes", url: "/admin/companies", icon: Users, requiredRole: "admin" }, { title: "Empresas & clientes", url: "/admin/companies", icon: Users, requiredRole: "admin" },
{ title: "Máquinas", url: "/admin/machines", icon: MonitorCog, requiredRole: "admin" },
{ title: "Campos personalizados", url: "/admin/fields", icon: Layers3, requiredRole: "admin" }, { title: "Campos personalizados", url: "/admin/fields", icon: Layers3, requiredRole: "admin" },
{ title: "SLAs", url: "/admin/slas", icon: Timer, requiredRole: "admin" }, { title: "SLAs", url: "/admin/slas", icon: Timer, requiredRole: "admin" },
{ title: "Alertas enviados", url: "/admin/alerts", icon: Gauge, requiredRole: "admin" }, { title: "Alertas enviados", url: "/admin/alerts", icon: Gauge, requiredRole: "admin" },

View file

@ -6,6 +6,9 @@ const envSchema = z.object({
NEXT_PUBLIC_CONVEX_URL: z.string().url().optional(), NEXT_PUBLIC_CONVEX_URL: z.string().url().optional(),
DATABASE_URL: z.string().min(1).optional(), DATABASE_URL: z.string().min(1).optional(),
NEXT_PUBLIC_APP_URL: z.string().url().optional(), NEXT_PUBLIC_APP_URL: z.string().url().optional(),
MACHINE_PROVISIONING_SECRET: z.string().optional(),
MACHINE_TOKEN_TTL_MS: z.coerce.number().optional(),
FLEET_SYNC_SECRET: z.string().optional(),
SMTP_ADDRESS: z.string().optional(), SMTP_ADDRESS: z.string().optional(),
SMTP_PORT: z.coerce.number().optional(), SMTP_PORT: z.coerce.number().optional(),
SMTP_DOMAIN: z.string().optional(), SMTP_DOMAIN: z.string().optional(),
@ -30,6 +33,9 @@ export const env = {
NEXT_PUBLIC_CONVEX_URL: parsed.data.NEXT_PUBLIC_CONVEX_URL, NEXT_PUBLIC_CONVEX_URL: parsed.data.NEXT_PUBLIC_CONVEX_URL,
DATABASE_URL: parsed.data.DATABASE_URL, DATABASE_URL: parsed.data.DATABASE_URL,
NEXT_PUBLIC_APP_URL: parsed.data.NEXT_PUBLIC_APP_URL, NEXT_PUBLIC_APP_URL: parsed.data.NEXT_PUBLIC_APP_URL,
MACHINE_PROVISIONING_SECRET: parsed.data.MACHINE_PROVISIONING_SECRET,
MACHINE_TOKEN_TTL_MS: parsed.data.MACHINE_TOKEN_TTL_MS,
FLEET_SYNC_SECRET: parsed.data.FLEET_SYNC_SECRET,
SMTP: parsed.data.SMTP_ADDRESS && parsed.data.SMTP_USERNAME && parsed.data.SMTP_PASSWORD SMTP: parsed.data.SMTP_ADDRESS && parsed.data.SMTP_USERNAME && parsed.data.SMTP_PASSWORD
? { ? {
host: parsed.data.SMTP_ADDRESS, host: parsed.data.SMTP_ADDRESS,

View file

@ -0,0 +1,61 @@
import { auth } from "@/lib/auth"
import { prisma } from "@/lib/prisma"
type EnsureMachineAccountParams = {
machineId: string
tenantId: string
hostname: string
machineToken: string
}
export async function ensureMachineAccount(params: EnsureMachineAccountParams) {
const { machineId, tenantId, hostname, machineToken } = params
const machineEmail = `machine-${machineId}@machines.local`
const context = await auth.$context
const passwordHash = await context.password.hash(machineToken)
const machineName = `Máquina ${hostname}`
const user = await prisma.authUser.upsert({
where: { email: machineEmail },
update: {
name: machineName,
tenantId,
role: "machine",
},
create: {
email: machineEmail,
name: machineName,
role: "machine",
tenantId,
},
})
await prisma.authAccount.upsert({
where: {
providerId_accountId: {
providerId: "credential",
accountId: machineEmail,
},
},
update: {
password: passwordHash,
userId: user.id,
},
create: {
providerId: "credential",
accountId: machineEmail,
userId: user.id,
password: passwordHash,
},
})
await prisma.authSession.deleteMany({
where: { userId: user.id },
})
return {
authUserId: user.id,
authEmail: machineEmail,
}
}