Compare commits
3 Commits
d1ea1a0efa
...
9dd5face01
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9dd5face01 | ||
|
|
76c32b2345 | ||
|
|
30928cd71d |
85
apps/web/src/app/[locale]/admin/audit/page.tsx
Normal file
85
apps/web/src/app/[locale]/admin/audit/page.tsx
Normal file
@@ -0,0 +1,85 @@
|
||||
import {
|
||||
createSearchParamsCache,
|
||||
parseAsArrayOf,
|
||||
parseAsInteger,
|
||||
parseAsString,
|
||||
} from "nuqs/server";
|
||||
import { Suspense } from "react";
|
||||
|
||||
import { getAuditResponseSchema } from "@turbostarter/api/schema";
|
||||
import { handle } from "@turbostarter/api/utils";
|
||||
import { pickBy } from "@turbostarter/shared/utils";
|
||||
import { DataTableSkeleton } from "@turbostarter/ui-web/data-table/data-table-skeleton";
|
||||
|
||||
import { api } from "~/lib/api/server";
|
||||
import { getMetadata } from "~/lib/metadata";
|
||||
import { AuditDataTable } from "~/modules/admin/audit/data-table/audit-data-table";
|
||||
import { getSortingStateParser } from "~/modules/common/hooks/use-data-table/common";
|
||||
import {
|
||||
DashboardHeader,
|
||||
DashboardHeaderDescription,
|
||||
DashboardHeaderTitle,
|
||||
} from "~/modules/common/layout/dashboard/header";
|
||||
|
||||
const searchParamsCache = createSearchParamsCache({
|
||||
page: parseAsInteger.withDefault(1),
|
||||
perPage: parseAsInteger.withDefault(50),
|
||||
sort: getSortingStateParser().withDefault([
|
||||
{ id: "createdAt", desc: true },
|
||||
]),
|
||||
q: parseAsString,
|
||||
eventType: parseAsArrayOf(parseAsString),
|
||||
meshId: parseAsArrayOf(parseAsString),
|
||||
createdAt: parseAsArrayOf(parseAsInteger),
|
||||
});
|
||||
|
||||
export const generateMetadata = getMetadata({
|
||||
title: "Audit · Admin",
|
||||
description: "Audit log of mesh events.",
|
||||
});
|
||||
|
||||
export default async function AuditPage(props: {
|
||||
searchParams: Promise<Record<string, string | string[] | undefined>>;
|
||||
}) {
|
||||
const searchParams = await props.searchParams;
|
||||
const { page, perPage, sort, ...rest } =
|
||||
searchParamsCache.parse(searchParams);
|
||||
|
||||
const filters = pickBy(rest, Boolean);
|
||||
|
||||
const promise = handle(api.admin.audit.$get, {
|
||||
schema: getAuditResponseSchema,
|
||||
})({
|
||||
query: {
|
||||
...filters,
|
||||
page: page.toString(),
|
||||
perPage: perPage.toString(),
|
||||
sort: JSON.stringify(sort),
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<DashboardHeader>
|
||||
<div>
|
||||
<DashboardHeaderTitle>Audit log</DashboardHeaderTitle>
|
||||
<DashboardHeaderDescription>
|
||||
Metadata-only event log — no message content, only routing.
|
||||
</DashboardHeaderDescription>
|
||||
</div>
|
||||
</DashboardHeader>
|
||||
<Suspense
|
||||
fallback={
|
||||
<DataTableSkeleton
|
||||
columnCount={5}
|
||||
filterCount={2}
|
||||
cellWidths={["8rem", "10rem", "8rem", "8rem", "10rem"]}
|
||||
shrinkZero
|
||||
/>
|
||||
}
|
||||
>
|
||||
<AuditDataTable promise={promise} perPage={perPage} />
|
||||
</Suspense>
|
||||
</>
|
||||
);
|
||||
}
|
||||
84
apps/web/src/app/[locale]/admin/invites/page.tsx
Normal file
84
apps/web/src/app/[locale]/admin/invites/page.tsx
Normal file
@@ -0,0 +1,84 @@
|
||||
import {
|
||||
createSearchParamsCache,
|
||||
parseAsBoolean,
|
||||
parseAsInteger,
|
||||
parseAsString,
|
||||
} from "nuqs/server";
|
||||
import { Suspense } from "react";
|
||||
|
||||
import { getInvitesResponseSchema } from "@turbostarter/api/schema";
|
||||
import { handle } from "@turbostarter/api/utils";
|
||||
import { pickBy } from "@turbostarter/shared/utils";
|
||||
import { DataTableSkeleton } from "@turbostarter/ui-web/data-table/data-table-skeleton";
|
||||
|
||||
import { api } from "~/lib/api/server";
|
||||
import { getMetadata } from "~/lib/metadata";
|
||||
import { InvitesDataTable } from "~/modules/admin/invites/data-table/invites-data-table";
|
||||
import { getSortingStateParser } from "~/modules/common/hooks/use-data-table/common";
|
||||
import {
|
||||
DashboardHeader,
|
||||
DashboardHeaderDescription,
|
||||
DashboardHeaderTitle,
|
||||
} from "~/modules/common/layout/dashboard/header";
|
||||
|
||||
const searchParamsCache = createSearchParamsCache({
|
||||
page: parseAsInteger.withDefault(1),
|
||||
perPage: parseAsInteger.withDefault(20),
|
||||
sort: getSortingStateParser().withDefault([
|
||||
{ id: "createdAt", desc: true },
|
||||
]),
|
||||
q: parseAsString,
|
||||
revoked: parseAsBoolean,
|
||||
expired: parseAsBoolean,
|
||||
});
|
||||
|
||||
export const generateMetadata = getMetadata({
|
||||
title: "Invites · Admin",
|
||||
description: "Mesh invite tokens across the system.",
|
||||
});
|
||||
|
||||
export default async function InvitesPage(props: {
|
||||
searchParams: Promise<Record<string, string | string[] | undefined>>;
|
||||
}) {
|
||||
const searchParams = await props.searchParams;
|
||||
const { page, perPage, sort, ...rest } =
|
||||
searchParamsCache.parse(searchParams);
|
||||
|
||||
const filters = pickBy(rest, Boolean);
|
||||
|
||||
const promise = handle(api.admin.invites.$get, {
|
||||
schema: getInvitesResponseSchema,
|
||||
})({
|
||||
query: {
|
||||
...filters,
|
||||
page: page.toString(),
|
||||
perPage: perPage.toString(),
|
||||
sort: JSON.stringify(sort),
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<DashboardHeader>
|
||||
<div>
|
||||
<DashboardHeaderTitle>Invites</DashboardHeaderTitle>
|
||||
<DashboardHeaderDescription>
|
||||
Mesh invite tokens — active, revoked, expired, exhausted.
|
||||
</DashboardHeaderDescription>
|
||||
</div>
|
||||
</DashboardHeader>
|
||||
<Suspense
|
||||
fallback={
|
||||
<DataTableSkeleton
|
||||
columnCount={6}
|
||||
filterCount={2}
|
||||
cellWidths={["12rem", "8rem", "5rem", "5rem", "7rem", "5rem"]}
|
||||
shrinkZero
|
||||
/>
|
||||
}
|
||||
>
|
||||
<InvitesDataTable promise={promise} perPage={perPage} />
|
||||
</Suspense>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -35,6 +35,31 @@ const menu = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
label: "mesh",
|
||||
items: [
|
||||
{
|
||||
title: "meshes",
|
||||
href: pathsConfig.admin.meshes.index,
|
||||
icon: Icons.Share,
|
||||
},
|
||||
{
|
||||
title: "sessions",
|
||||
href: pathsConfig.admin.sessions.index,
|
||||
icon: Icons.Activity,
|
||||
},
|
||||
{
|
||||
title: "invites",
|
||||
href: pathsConfig.admin.invites.index,
|
||||
icon: Icons.Link,
|
||||
},
|
||||
{
|
||||
title: "audit",
|
||||
href: pathsConfig.admin.audit.index,
|
||||
icon: Icons.ScrollText,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
export default async function AdminLayout({
|
||||
|
||||
277
apps/web/src/app/[locale]/admin/meshes/[id]/page.tsx
Normal file
277
apps/web/src/app/[locale]/admin/meshes/[id]/page.tsx
Normal file
@@ -0,0 +1,277 @@
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { getMeshResponseSchema } from "@turbostarter/api/schema";
|
||||
import { handle } from "@turbostarter/api/utils";
|
||||
import { Badge } from "@turbostarter/ui-web/badge";
|
||||
|
||||
import { api } from "~/lib/api/server";
|
||||
import { getMetadata } from "~/lib/metadata";
|
||||
import {
|
||||
DashboardHeader,
|
||||
DashboardHeaderDescription,
|
||||
DashboardHeaderTitle,
|
||||
} from "~/modules/common/layout/dashboard/header";
|
||||
|
||||
export const generateMetadata = getMetadata({
|
||||
title: "Mesh detail · Admin",
|
||||
description: "Members, presences, invites, audit events for a mesh.",
|
||||
});
|
||||
|
||||
export default async function MeshDetailPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>;
|
||||
}) {
|
||||
const { id } = await params;
|
||||
|
||||
const data = await handle(api.admin.meshes[":id"].$get, {
|
||||
schema: getMeshResponseSchema,
|
||||
})({ param: { id } }).catch(() => null);
|
||||
|
||||
if (!data || !data.mesh) notFound();
|
||||
|
||||
const { mesh, members, presences, invites, auditEvents } = data;
|
||||
|
||||
return (
|
||||
<>
|
||||
<DashboardHeader>
|
||||
<div>
|
||||
<DashboardHeaderTitle>
|
||||
<span className="flex items-center gap-3">
|
||||
{mesh.name}
|
||||
<Badge variant="outline" className="font-mono text-xs">
|
||||
{mesh.slug}
|
||||
</Badge>
|
||||
</span>
|
||||
</DashboardHeaderTitle>
|
||||
<DashboardHeaderDescription>
|
||||
Owner: {mesh.ownerName ?? "—"} · {mesh.ownerEmail ?? "—"} · tier{" "}
|
||||
{mesh.tier} · transport {mesh.transport} · visibility{" "}
|
||||
{mesh.visibility}
|
||||
</DashboardHeaderDescription>
|
||||
</div>
|
||||
</DashboardHeader>
|
||||
|
||||
<div className="grid gap-8">
|
||||
<Section
|
||||
title="Members"
|
||||
count={members.length}
|
||||
empty="No members yet."
|
||||
>
|
||||
<table className="w-full text-sm">
|
||||
<thead className="text-muted-foreground border-b text-left text-xs uppercase">
|
||||
<tr>
|
||||
<th className="px-3 py-2 font-medium">Display name</th>
|
||||
<th className="px-3 py-2 font-medium">Role</th>
|
||||
<th className="px-3 py-2 font-medium">Pubkey</th>
|
||||
<th className="px-3 py-2 font-medium">Joined</th>
|
||||
<th className="px-3 py-2 font-medium">Last seen</th>
|
||||
<th className="px-3 py-2 font-medium">Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y">
|
||||
{members.map((m) => (
|
||||
<tr key={m.id}>
|
||||
<td className="px-3 py-2 font-medium">{m.displayName}</td>
|
||||
<td className="px-3 py-2">
|
||||
<Badge variant="outline">{m.role}</Badge>
|
||||
</td>
|
||||
<td className="text-muted-foreground px-3 py-2 font-mono text-xs">
|
||||
{m.peerPubkey.slice(0, 12)}…
|
||||
</td>
|
||||
<td className="text-muted-foreground px-3 py-2">
|
||||
{new Date(m.joinedAt).toLocaleDateString()}
|
||||
</td>
|
||||
<td className="text-muted-foreground px-3 py-2">
|
||||
{m.lastSeenAt
|
||||
? new Date(m.lastSeenAt).toLocaleString()
|
||||
: "—"}
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
{m.revokedAt ? (
|
||||
<Badge className="bg-destructive/15 text-destructive">
|
||||
revoked
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge className="bg-success/15 text-success">
|
||||
active
|
||||
</Badge>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</Section>
|
||||
|
||||
<Section
|
||||
title="Live presences"
|
||||
count={presences.length}
|
||||
empty="No active sessions."
|
||||
>
|
||||
<table className="w-full text-sm">
|
||||
<thead className="text-muted-foreground border-b text-left text-xs uppercase">
|
||||
<tr>
|
||||
<th className="px-3 py-2 font-medium">Peer</th>
|
||||
<th className="px-3 py-2 font-medium">Status</th>
|
||||
<th className="px-3 py-2 font-medium">PID</th>
|
||||
<th className="px-3 py-2 font-medium">CWD</th>
|
||||
<th className="px-3 py-2 font-medium">Last ping</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y">
|
||||
{presences.map((p) => (
|
||||
<tr key={p.id}>
|
||||
<td className="px-3 py-2 font-medium">
|
||||
{p.displayName ?? "—"}
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className={
|
||||
p.disconnectedAt
|
||||
? "bg-muted/50 text-muted-foreground"
|
||||
: p.status === "working"
|
||||
? "bg-primary/15 text-primary"
|
||||
: p.status === "dnd"
|
||||
? "bg-destructive/15 text-destructive"
|
||||
: "bg-muted text-muted-foreground"
|
||||
}
|
||||
>
|
||||
{p.disconnectedAt ? "disconnected" : p.status}
|
||||
</Badge>
|
||||
</td>
|
||||
<td className="text-muted-foreground px-3 py-2 font-mono text-xs">
|
||||
{p.pid}
|
||||
</td>
|
||||
<td className="text-muted-foreground max-w-xs truncate px-3 py-2 font-mono text-xs">
|
||||
{p.cwd}
|
||||
</td>
|
||||
<td className="text-muted-foreground px-3 py-2">
|
||||
{new Date(p.lastPingAt).toLocaleTimeString()}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</Section>
|
||||
|
||||
<Section
|
||||
title="Invites"
|
||||
count={invites.length}
|
||||
empty="No invites issued."
|
||||
>
|
||||
<table className="w-full text-sm">
|
||||
<thead className="text-muted-foreground border-b text-left text-xs uppercase">
|
||||
<tr>
|
||||
<th className="px-3 py-2 font-medium">Token</th>
|
||||
<th className="px-3 py-2 font-medium">Role</th>
|
||||
<th className="px-3 py-2 font-medium">Uses</th>
|
||||
<th className="px-3 py-2 font-medium">Expires</th>
|
||||
<th className="px-3 py-2 font-medium">Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y">
|
||||
{invites.map((inv) => (
|
||||
<tr key={inv.id}>
|
||||
<td className="text-muted-foreground px-3 py-2 font-mono text-xs">
|
||||
{inv.token.slice(0, 12)}…
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
<Badge variant="outline">{inv.role}</Badge>
|
||||
</td>
|
||||
<td className="px-3 py-2 font-mono">
|
||||
{inv.usedCount} / {inv.maxUses}
|
||||
</td>
|
||||
<td className="text-muted-foreground px-3 py-2">
|
||||
{new Date(inv.expiresAt).toLocaleDateString()}
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
{inv.revokedAt ? (
|
||||
<Badge className="bg-destructive/15 text-destructive">
|
||||
revoked
|
||||
</Badge>
|
||||
) : new Date(inv.expiresAt) < new Date() ? (
|
||||
<Badge variant="outline">expired</Badge>
|
||||
) : (
|
||||
<Badge className="bg-success/15 text-success">
|
||||
active
|
||||
</Badge>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</Section>
|
||||
|
||||
<Section
|
||||
title="Last 50 audit events"
|
||||
count={auditEvents.length}
|
||||
empty="No events yet."
|
||||
>
|
||||
<table className="w-full text-sm">
|
||||
<thead className="text-muted-foreground border-b text-left text-xs uppercase">
|
||||
<tr>
|
||||
<th className="px-3 py-2 font-medium">When</th>
|
||||
<th className="px-3 py-2 font-medium">Event</th>
|
||||
<th className="px-3 py-2 font-medium">Actor</th>
|
||||
<th className="px-3 py-2 font-medium">Target</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y">
|
||||
{auditEvents.map((e) => (
|
||||
<tr key={e.id}>
|
||||
<td className="text-muted-foreground px-3 py-2 font-mono text-xs whitespace-nowrap">
|
||||
{new Date(e.createdAt).toLocaleString()}
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
<Badge variant="outline" className="font-mono text-xs">
|
||||
{e.eventType}
|
||||
</Badge>
|
||||
</td>
|
||||
<td className="text-muted-foreground px-3 py-2 font-mono text-xs">
|
||||
{e.actorPeerId?.slice(0, 12) ?? "—"}
|
||||
</td>
|
||||
<td className="text-muted-foreground px-3 py-2 font-mono text-xs">
|
||||
{e.targetPeerId?.slice(0, 12) ?? "—"}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</Section>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Section({
|
||||
title,
|
||||
count,
|
||||
empty,
|
||||
children,
|
||||
}: {
|
||||
title: string;
|
||||
count: number;
|
||||
empty: string;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<section className="rounded-lg border">
|
||||
<header className="flex items-center justify-between border-b px-4 py-3">
|
||||
<h2 className="font-medium">{title}</h2>
|
||||
<Badge variant="outline" className="font-mono text-xs">
|
||||
{count}
|
||||
</Badge>
|
||||
</header>
|
||||
{count === 0 ? (
|
||||
<p className="text-muted-foreground px-4 py-8 text-center text-sm">
|
||||
{empty}
|
||||
</p>
|
||||
) : (
|
||||
<div className="overflow-x-auto">{children}</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
93
apps/web/src/app/[locale]/admin/meshes/page.tsx
Normal file
93
apps/web/src/app/[locale]/admin/meshes/page.tsx
Normal file
@@ -0,0 +1,93 @@
|
||||
import {
|
||||
createSearchParamsCache,
|
||||
parseAsArrayOf,
|
||||
parseAsBoolean,
|
||||
parseAsInteger,
|
||||
parseAsString,
|
||||
parseAsStringEnum,
|
||||
} from "nuqs/server";
|
||||
import { Suspense } from "react";
|
||||
|
||||
import { getMeshesResponseSchema } from "@turbostarter/api/schema";
|
||||
import { handle } from "@turbostarter/api/utils";
|
||||
import { pickBy } from "@turbostarter/shared/utils";
|
||||
import { DataTableSkeleton } from "@turbostarter/ui-web/data-table/data-table-skeleton";
|
||||
|
||||
import { api } from "~/lib/api/server";
|
||||
import { getMetadata } from "~/lib/metadata";
|
||||
import { MeshesDataTable } from "~/modules/admin/meshes/data-table/meshes-data-table";
|
||||
import { getSortingStateParser } from "~/modules/common/hooks/use-data-table/common";
|
||||
import {
|
||||
DashboardHeader,
|
||||
DashboardHeaderDescription,
|
||||
DashboardHeaderTitle,
|
||||
} from "~/modules/common/layout/dashboard/header";
|
||||
|
||||
const TIER_VALUES = ["free", "pro", "team", "enterprise"] as const;
|
||||
const TRANSPORT_VALUES = ["managed", "tailscale", "self_hosted"] as const;
|
||||
const VISIBILITY_VALUES = ["private", "public"] as const;
|
||||
|
||||
const searchParamsCache = createSearchParamsCache({
|
||||
page: parseAsInteger.withDefault(1),
|
||||
perPage: parseAsInteger.withDefault(20),
|
||||
sort: getSortingStateParser().withDefault([
|
||||
{ id: "createdAt", desc: true },
|
||||
]),
|
||||
q: parseAsString,
|
||||
tier: parseAsArrayOf(parseAsStringEnum([...TIER_VALUES])),
|
||||
transport: parseAsArrayOf(parseAsStringEnum([...TRANSPORT_VALUES])),
|
||||
visibility: parseAsArrayOf(parseAsStringEnum([...VISIBILITY_VALUES])),
|
||||
archived: parseAsBoolean,
|
||||
createdAt: parseAsArrayOf(parseAsInteger),
|
||||
});
|
||||
|
||||
export const generateMetadata = getMetadata({
|
||||
title: "Meshes · Admin",
|
||||
description: "All meshes in the system.",
|
||||
});
|
||||
|
||||
export default async function MeshesPage(props: {
|
||||
searchParams: Promise<Record<string, string | string[] | undefined>>;
|
||||
}) {
|
||||
const searchParams = await props.searchParams;
|
||||
const { page, perPage, sort, ...rest } =
|
||||
searchParamsCache.parse(searchParams);
|
||||
|
||||
const filters = pickBy(rest, Boolean);
|
||||
|
||||
const promise = handle(api.admin.meshes.$get, {
|
||||
schema: getMeshesResponseSchema,
|
||||
})({
|
||||
query: {
|
||||
...filters,
|
||||
page: page.toString(),
|
||||
perPage: perPage.toString(),
|
||||
sort: JSON.stringify(sort),
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<DashboardHeader>
|
||||
<div>
|
||||
<DashboardHeaderTitle>Meshes</DashboardHeaderTitle>
|
||||
<DashboardHeaderDescription>
|
||||
All meshes across the system — tier, transport, owner, member count.
|
||||
</DashboardHeaderDescription>
|
||||
</div>
|
||||
</DashboardHeader>
|
||||
<Suspense
|
||||
fallback={
|
||||
<DataTableSkeleton
|
||||
columnCount={6}
|
||||
filterCount={3}
|
||||
cellWidths={["14rem", "12rem", "6rem", "6rem", "5rem", "6rem"]}
|
||||
shrinkZero
|
||||
/>
|
||||
}
|
||||
>
|
||||
<MeshesDataTable promise={promise} perPage={perPage} />
|
||||
</Suspense>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -35,12 +35,65 @@ export default async function AdminPage() {
|
||||
organizations: z.number(),
|
||||
customers: z.number(),
|
||||
});
|
||||
const meshSummarySchema = z.object({
|
||||
meshes: z.number(),
|
||||
activeMeshes: z.number(),
|
||||
totalPresences: z.number(),
|
||||
activePresences: z.number(),
|
||||
messages24h: z.number(),
|
||||
});
|
||||
|
||||
const data = await handle(api.admin.summary.$get, {
|
||||
schema: adminSummarySchema,
|
||||
})();
|
||||
const [base, mesh] = await Promise.all([
|
||||
handle(api.admin.summary.$get, { schema: adminSummarySchema })(),
|
||||
handle(api.admin.summary.mesh.$get, { schema: meshSummarySchema })(),
|
||||
]);
|
||||
|
||||
const cards = ["users", "organizations", "customers"] as const;
|
||||
const nf = new Intl.NumberFormat(i18n.language);
|
||||
|
||||
const cards = [
|
||||
{
|
||||
key: "users" as const,
|
||||
title: t("common:users"),
|
||||
description: t("home.summary.users"),
|
||||
href: pathsConfig.admin.users.index,
|
||||
value: base.users,
|
||||
},
|
||||
{
|
||||
key: "organizations" as const,
|
||||
title: t("common:organizations"),
|
||||
description: t("home.summary.organizations"),
|
||||
href: pathsConfig.admin.organizations.index,
|
||||
value: base.organizations,
|
||||
},
|
||||
{
|
||||
key: "customers" as const,
|
||||
title: t("common:customers"),
|
||||
description: t("home.summary.customers"),
|
||||
href: pathsConfig.admin.customers.index,
|
||||
value: base.customers,
|
||||
},
|
||||
{
|
||||
key: "meshes" as const,
|
||||
title: "Meshes",
|
||||
description: `${nf.format(mesh.activeMeshes)} active`,
|
||||
href: pathsConfig.admin.meshes.index,
|
||||
value: mesh.meshes,
|
||||
},
|
||||
{
|
||||
key: "sessions" as const,
|
||||
title: "Sessions",
|
||||
description: `${nf.format(mesh.activePresences)} live now`,
|
||||
href: pathsConfig.admin.sessions.index,
|
||||
value: mesh.totalPresences,
|
||||
},
|
||||
{
|
||||
key: "messages" as const,
|
||||
title: "Messages (24h)",
|
||||
description: "Routed through the broker",
|
||||
href: pathsConfig.admin.audit.index,
|
||||
value: mesh.messages24h,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -57,10 +110,10 @@ export default async function AdminPage() {
|
||||
|
||||
<nav className="@container/stats w-full">
|
||||
<ul className="grid grid-cols-1 gap-4 @lg/stats:grid-cols-2 @2xl/stats:grid-cols-3">
|
||||
{cards.map((key) => (
|
||||
<li key={key}>
|
||||
{cards.map((card) => (
|
||||
<li key={card.key}>
|
||||
<TurboLink
|
||||
href={pathsConfig.admin[key].index}
|
||||
href={card.href}
|
||||
className={cn(
|
||||
buttonVariants({ variant: "outline" }),
|
||||
"text-muted-foreground h-full w-full flex-col items-start justify-between gap-3 p-0",
|
||||
@@ -69,18 +122,17 @@ export default async function AdminPage() {
|
||||
<CardHeader className="w-full">
|
||||
<div className="flex w-full items-center justify-between gap-3">
|
||||
<CardTitle className="text-foreground truncate">
|
||||
{t(`common:${key}`)}
|
||||
{card.title}
|
||||
</CardTitle>
|
||||
<Icons.ChevronRight className="mt-0.5 size-4" />
|
||||
</div>
|
||||
<CardDescription className="whitespace-normal">
|
||||
{t(`home.summary.${key}`)}
|
||||
{card.description}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
|
||||
<CardFooter>
|
||||
<span className="text-foreground font-mono text-4xl font-bold tracking-tight">
|
||||
{new Intl.NumberFormat(i18n.language).format(data[key])}
|
||||
{nf.format(card.value)}
|
||||
</span>
|
||||
</CardFooter>
|
||||
</TurboLink>
|
||||
|
||||
88
apps/web/src/app/[locale]/admin/sessions/page.tsx
Normal file
88
apps/web/src/app/[locale]/admin/sessions/page.tsx
Normal file
@@ -0,0 +1,88 @@
|
||||
import {
|
||||
createSearchParamsCache,
|
||||
parseAsArrayOf,
|
||||
parseAsBoolean,
|
||||
parseAsInteger,
|
||||
parseAsString,
|
||||
parseAsStringEnum,
|
||||
} from "nuqs/server";
|
||||
import { Suspense } from "react";
|
||||
|
||||
import { getSessionsResponseSchema } from "@turbostarter/api/schema";
|
||||
import { handle } from "@turbostarter/api/utils";
|
||||
import { pickBy } from "@turbostarter/shared/utils";
|
||||
import { DataTableSkeleton } from "@turbostarter/ui-web/data-table/data-table-skeleton";
|
||||
|
||||
import { api } from "~/lib/api/server";
|
||||
import { getMetadata } from "~/lib/metadata";
|
||||
import { SessionsDataTable } from "~/modules/admin/sessions/data-table/sessions-data-table";
|
||||
import { getSortingStateParser } from "~/modules/common/hooks/use-data-table/common";
|
||||
import {
|
||||
DashboardHeader,
|
||||
DashboardHeaderDescription,
|
||||
DashboardHeaderTitle,
|
||||
} from "~/modules/common/layout/dashboard/header";
|
||||
|
||||
const STATUS_VALUES = ["idle", "working", "dnd"] as const;
|
||||
|
||||
const searchParamsCache = createSearchParamsCache({
|
||||
page: parseAsInteger.withDefault(1),
|
||||
perPage: parseAsInteger.withDefault(20),
|
||||
sort: getSortingStateParser().withDefault([
|
||||
{ id: "lastPingAt", desc: true },
|
||||
]),
|
||||
q: parseAsString,
|
||||
status: parseAsArrayOf(parseAsStringEnum([...STATUS_VALUES])),
|
||||
active: parseAsBoolean,
|
||||
});
|
||||
|
||||
export const generateMetadata = getMetadata({
|
||||
title: "Sessions · Admin",
|
||||
description: "Live Claude Code sessions across all meshes.",
|
||||
});
|
||||
|
||||
export default async function SessionsPage(props: {
|
||||
searchParams: Promise<Record<string, string | string[] | undefined>>;
|
||||
}) {
|
||||
const searchParams = await props.searchParams;
|
||||
const { page, perPage, sort, ...rest } =
|
||||
searchParamsCache.parse(searchParams);
|
||||
|
||||
const filters = pickBy(rest, Boolean);
|
||||
|
||||
const promise = handle(api.admin.sessions.$get, {
|
||||
schema: getSessionsResponseSchema,
|
||||
})({
|
||||
query: {
|
||||
...filters,
|
||||
page: page.toString(),
|
||||
perPage: perPage.toString(),
|
||||
sort: JSON.stringify(sort),
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<DashboardHeader>
|
||||
<div>
|
||||
<DashboardHeaderTitle>Sessions</DashboardHeaderTitle>
|
||||
<DashboardHeaderDescription>
|
||||
Live Claude Code presences across every mesh.
|
||||
</DashboardHeaderDescription>
|
||||
</div>
|
||||
</DashboardHeader>
|
||||
<Suspense
|
||||
fallback={
|
||||
<DataTableSkeleton
|
||||
columnCount={5}
|
||||
filterCount={2}
|
||||
cellWidths={["6rem", "10rem", "12rem", "14rem", "6rem"]}
|
||||
shrinkZero
|
||||
/>
|
||||
}
|
||||
>
|
||||
<SessionsDataTable promise={promise} perPage={perPage} />
|
||||
</Suspense>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -54,6 +54,19 @@ const pathsConfig = {
|
||||
index: `${ADMIN_PREFIX}/customers`,
|
||||
customer: (id: string) => `${ADMIN_PREFIX}/customers/${id}`,
|
||||
},
|
||||
meshes: {
|
||||
index: `${ADMIN_PREFIX}/meshes`,
|
||||
mesh: (id: string) => `${ADMIN_PREFIX}/meshes/${id}`,
|
||||
},
|
||||
sessions: {
|
||||
index: `${ADMIN_PREFIX}/sessions`,
|
||||
},
|
||||
invites: {
|
||||
index: `${ADMIN_PREFIX}/invites`,
|
||||
},
|
||||
audit: {
|
||||
index: `${ADMIN_PREFIX}/audit`,
|
||||
},
|
||||
},
|
||||
marketing: {
|
||||
pricing: "/pricing",
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
"use client";
|
||||
|
||||
import { use } from "react";
|
||||
|
||||
import { DataTable } from "@turbostarter/ui-web/data-table/data-table";
|
||||
import { DataTableToolbar } from "@turbostarter/ui-web/data-table/data-table-toolbar";
|
||||
|
||||
import { useDataTable } from "~/modules/common/hooks/use-data-table";
|
||||
|
||||
import { useAuditColumns } from "./columns";
|
||||
|
||||
import type { GetAuditResponse } from "@turbostarter/api/schema";
|
||||
|
||||
interface Props {
|
||||
readonly promise: Promise<Awaited<GetAuditResponse>>;
|
||||
readonly perPage: number;
|
||||
}
|
||||
|
||||
export const AuditDataTable = ({ promise, perPage }: Props) => {
|
||||
const columns = useAuditColumns();
|
||||
const { data, total } = use(promise);
|
||||
|
||||
const { table } = useDataTable({
|
||||
persistance: "searchParams",
|
||||
data,
|
||||
columns,
|
||||
pageCount: Math.ceil(total / perPage),
|
||||
initialState: {
|
||||
sorting: [{ id: "createdAt", desc: true }],
|
||||
columnVisibility: { q: false },
|
||||
},
|
||||
shallow: false,
|
||||
clearOnDefault: true,
|
||||
enableRowSelection: false,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex w-full flex-col gap-2">
|
||||
<DataTableToolbar table={table} />
|
||||
<DataTable table={table} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
98
apps/web/src/modules/admin/audit/data-table/columns.tsx
Normal file
98
apps/web/src/modules/admin/audit/data-table/columns.tsx
Normal file
@@ -0,0 +1,98 @@
|
||||
import { Badge } from "@turbostarter/ui-web/badge";
|
||||
import { DataTableColumnHeader } from "@turbostarter/ui-web/data-table/data-table-column-header";
|
||||
|
||||
import { TurboLink } from "~/modules/common/turbo-link";
|
||||
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import type { GetAuditResponse } from "@turbostarter/api/schema";
|
||||
|
||||
type Audit = GetAuditResponse["data"][number];
|
||||
|
||||
export const useAuditColumns = (): ColumnDef<Audit>[] => [
|
||||
{
|
||||
id: "q",
|
||||
accessorKey: "q",
|
||||
meta: {
|
||||
placeholder: "Search by event, peer, mesh…",
|
||||
variant: "text",
|
||||
},
|
||||
enableHiding: false,
|
||||
enableColumnFilter: true,
|
||||
},
|
||||
{
|
||||
id: "eventType",
|
||||
accessorKey: "eventType",
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title="Event" />
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<Badge variant="outline" className="font-mono text-xs">
|
||||
{row.original.eventType}
|
||||
</Badge>
|
||||
),
|
||||
meta: { label: "Event" },
|
||||
},
|
||||
{
|
||||
id: "mesh",
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title="Mesh" />
|
||||
),
|
||||
cell: ({ row }) =>
|
||||
row.original.meshId ? (
|
||||
<TurboLink
|
||||
href={`/admin/meshes/${row.original.meshId}`}
|
||||
className="group flex flex-col gap-0.5"
|
||||
>
|
||||
<span className="group-hover:text-primary text-sm underline underline-offset-4">
|
||||
{row.original.meshName ?? "—"}
|
||||
</span>
|
||||
</TurboLink>
|
||||
) : (
|
||||
<span className="text-muted-foreground">—</span>
|
||||
),
|
||||
meta: { label: "Mesh" },
|
||||
},
|
||||
{
|
||||
id: "actor",
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title="Actor" />
|
||||
),
|
||||
cell: ({ row }) =>
|
||||
row.original.actorPeerId ? (
|
||||
<code className="text-muted-foreground font-mono text-xs">
|
||||
{row.original.actorPeerId.slice(0, 12)}…
|
||||
</code>
|
||||
) : (
|
||||
<span className="text-muted-foreground">—</span>
|
||||
),
|
||||
meta: { label: "Actor" },
|
||||
},
|
||||
{
|
||||
id: "target",
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title="Target" />
|
||||
),
|
||||
cell: ({ row }) =>
|
||||
row.original.targetPeerId ? (
|
||||
<code className="text-muted-foreground font-mono text-xs">
|
||||
{row.original.targetPeerId.slice(0, 12)}…
|
||||
</code>
|
||||
) : (
|
||||
<span className="text-muted-foreground">—</span>
|
||||
),
|
||||
meta: { label: "Target" },
|
||||
},
|
||||
{
|
||||
id: "createdAt",
|
||||
accessorKey: "createdAt",
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title="When" />
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-muted-foreground text-sm">
|
||||
{new Date(row.original.createdAt).toLocaleString()}
|
||||
</span>
|
||||
),
|
||||
meta: { label: "When" },
|
||||
},
|
||||
];
|
||||
123
apps/web/src/modules/admin/invites/data-table/columns.tsx
Normal file
123
apps/web/src/modules/admin/invites/data-table/columns.tsx
Normal file
@@ -0,0 +1,123 @@
|
||||
import { Badge } from "@turbostarter/ui-web/badge";
|
||||
import { DataTableColumnHeader } from "@turbostarter/ui-web/data-table/data-table-column-header";
|
||||
|
||||
import { TurboLink } from "~/modules/common/turbo-link";
|
||||
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import type { GetInvitesResponse } from "@turbostarter/api/schema";
|
||||
|
||||
type Invite = GetInvitesResponse["data"][number];
|
||||
|
||||
export const useInviteColumns = (): ColumnDef<Invite>[] => [
|
||||
{
|
||||
id: "q",
|
||||
accessorKey: "q",
|
||||
meta: { placeholder: "Search by mesh or token…", variant: "text" },
|
||||
enableHiding: false,
|
||||
enableColumnFilter: true,
|
||||
},
|
||||
{
|
||||
id: "mesh",
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title="Mesh" />
|
||||
),
|
||||
cell: ({ row }) =>
|
||||
row.original.meshId ? (
|
||||
<TurboLink
|
||||
href={`/admin/meshes/${row.original.meshId}`}
|
||||
className="group flex flex-col gap-0.5"
|
||||
>
|
||||
<span className="group-hover:text-primary text-sm font-medium underline underline-offset-4">
|
||||
{row.original.meshName ?? "—"}
|
||||
</span>
|
||||
<span className="text-muted-foreground font-mono text-xs">
|
||||
{row.original.meshSlug ?? "—"}
|
||||
</span>
|
||||
</TurboLink>
|
||||
) : (
|
||||
<span className="text-muted-foreground">—</span>
|
||||
),
|
||||
meta: { label: "Mesh" },
|
||||
enableHiding: false,
|
||||
},
|
||||
{
|
||||
id: "token",
|
||||
accessorKey: "token",
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title="Token" />
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<code className="bg-muted text-muted-foreground rounded px-2 py-0.5 text-xs">
|
||||
{row.original.token.slice(0, 12)}…
|
||||
</code>
|
||||
),
|
||||
meta: { label: "Token" },
|
||||
},
|
||||
{
|
||||
id: "role",
|
||||
accessorKey: "role",
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title="Role" />
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<Badge variant="outline">{row.original.role}</Badge>
|
||||
),
|
||||
meta: { label: "Role" },
|
||||
},
|
||||
{
|
||||
id: "uses",
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title="Uses" />
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<span className="font-mono text-sm">
|
||||
{row.original.usedCount} / {row.original.maxUses}
|
||||
</span>
|
||||
),
|
||||
meta: { label: "Uses" },
|
||||
},
|
||||
{
|
||||
id: "expiresAt",
|
||||
accessorKey: "expiresAt",
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title="Expires" />
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const expired = new Date(row.original.expiresAt) < new Date();
|
||||
return (
|
||||
<span
|
||||
className={
|
||||
"text-sm " + (expired ? "text-destructive" : "text-muted-foreground")
|
||||
}
|
||||
>
|
||||
{new Date(row.original.expiresAt).toLocaleDateString()}
|
||||
{expired && " (expired)"}
|
||||
</span>
|
||||
);
|
||||
},
|
||||
meta: { label: "Expires" },
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title="Status" />
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
if (row.original.revokedAt) {
|
||||
return (
|
||||
<Badge className="bg-destructive/15 text-destructive">revoked</Badge>
|
||||
);
|
||||
}
|
||||
if (new Date(row.original.expiresAt) < new Date()) {
|
||||
return <Badge variant="outline">expired</Badge>;
|
||||
}
|
||||
if (row.original.usedCount >= row.original.maxUses) {
|
||||
return <Badge variant="outline">exhausted</Badge>;
|
||||
}
|
||||
return (
|
||||
<Badge className="bg-success/15 text-success">active</Badge>
|
||||
);
|
||||
},
|
||||
meta: { label: "Status" },
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,43 @@
|
||||
"use client";
|
||||
|
||||
import { use } from "react";
|
||||
|
||||
import { DataTable } from "@turbostarter/ui-web/data-table/data-table";
|
||||
import { DataTableToolbar } from "@turbostarter/ui-web/data-table/data-table-toolbar";
|
||||
|
||||
import { useDataTable } from "~/modules/common/hooks/use-data-table";
|
||||
|
||||
import { useInviteColumns } from "./columns";
|
||||
|
||||
import type { GetInvitesResponse } from "@turbostarter/api/schema";
|
||||
|
||||
interface Props {
|
||||
readonly promise: Promise<Awaited<GetInvitesResponse>>;
|
||||
readonly perPage: number;
|
||||
}
|
||||
|
||||
export const InvitesDataTable = ({ promise, perPage }: Props) => {
|
||||
const columns = useInviteColumns();
|
||||
const { data, total } = use(promise);
|
||||
|
||||
const { table } = useDataTable({
|
||||
persistance: "searchParams",
|
||||
data,
|
||||
columns,
|
||||
pageCount: Math.ceil(total / perPage),
|
||||
initialState: {
|
||||
sorting: [{ id: "createdAt", desc: true }],
|
||||
columnVisibility: { q: false },
|
||||
},
|
||||
shallow: false,
|
||||
clearOnDefault: true,
|
||||
enableRowSelection: false,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex w-full flex-col gap-2">
|
||||
<DataTableToolbar table={table} />
|
||||
<DataTable table={table} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
145
apps/web/src/modules/admin/meshes/data-table/columns.tsx
Normal file
145
apps/web/src/modules/admin/meshes/data-table/columns.tsx
Normal file
@@ -0,0 +1,145 @@
|
||||
import { Badge } from "@turbostarter/ui-web/badge";
|
||||
import { DataTableColumnHeader } from "@turbostarter/ui-web/data-table/data-table-column-header";
|
||||
|
||||
import { TurboLink } from "~/modules/common/turbo-link";
|
||||
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import type { GetMeshesResponse } from "@turbostarter/api/schema";
|
||||
|
||||
type Mesh = GetMeshesResponse["data"][number];
|
||||
|
||||
const TIER_COLORS: Record<string, string> = {
|
||||
free: "bg-muted text-muted-foreground",
|
||||
pro: "bg-blue-500/15 text-blue-600",
|
||||
team: "bg-purple-500/15 text-purple-600",
|
||||
enterprise: "bg-amber-500/15 text-amber-600",
|
||||
};
|
||||
|
||||
const TRANSPORT_COLORS: Record<string, string> = {
|
||||
managed: "bg-primary/15 text-primary",
|
||||
tailscale: "bg-emerald-500/15 text-emerald-600",
|
||||
self_hosted: "bg-zinc-500/15 text-zinc-600",
|
||||
};
|
||||
|
||||
export const useMeshColumns = (): ColumnDef<Mesh>[] => [
|
||||
{
|
||||
id: "q",
|
||||
accessorKey: "q",
|
||||
meta: { placeholder: "Search by name or slug…", variant: "text" },
|
||||
enableHiding: false,
|
||||
enableColumnFilter: true,
|
||||
},
|
||||
{
|
||||
id: "name",
|
||||
accessorKey: "name",
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title="Mesh" />
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<TurboLink
|
||||
href={`/admin/meshes/${row.original.id}`}
|
||||
className="group flex flex-col gap-0.5"
|
||||
>
|
||||
<span className="group-hover:text-primary truncate font-medium underline underline-offset-4">
|
||||
{row.original.name}
|
||||
</span>
|
||||
<span className="text-muted-foreground font-mono text-xs">
|
||||
{row.original.slug}
|
||||
</span>
|
||||
</TurboLink>
|
||||
),
|
||||
enableHiding: false,
|
||||
},
|
||||
{
|
||||
id: "owner",
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title="Owner" />
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="truncate text-sm font-medium">
|
||||
{row.original.ownerName ?? "—"}
|
||||
</span>
|
||||
<span className="text-muted-foreground truncate text-xs">
|
||||
{row.original.ownerEmail ?? "—"}
|
||||
</span>
|
||||
</div>
|
||||
),
|
||||
meta: { label: "Owner" },
|
||||
},
|
||||
{
|
||||
id: "tier",
|
||||
accessorKey: "tier",
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title="Tier" />
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className={TIER_COLORS[row.original.tier] ?? ""}
|
||||
>
|
||||
{row.original.tier}
|
||||
</Badge>
|
||||
),
|
||||
meta: {
|
||||
label: "Tier",
|
||||
variant: "multiSelect",
|
||||
options: [
|
||||
{ label: "Free", value: "free" },
|
||||
{ label: "Pro", value: "pro" },
|
||||
{ label: "Team", value: "team" },
|
||||
{ label: "Enterprise", value: "enterprise" },
|
||||
],
|
||||
},
|
||||
enableColumnFilter: true,
|
||||
},
|
||||
{
|
||||
id: "transport",
|
||||
accessorKey: "transport",
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title="Transport" />
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className={TRANSPORT_COLORS[row.original.transport] ?? ""}
|
||||
>
|
||||
{row.original.transport}
|
||||
</Badge>
|
||||
),
|
||||
meta: {
|
||||
label: "Transport",
|
||||
variant: "multiSelect",
|
||||
options: [
|
||||
{ label: "Managed", value: "managed" },
|
||||
{ label: "Tailscale", value: "tailscale" },
|
||||
{ label: "Self-hosted", value: "self_hosted" },
|
||||
],
|
||||
},
|
||||
enableColumnFilter: true,
|
||||
},
|
||||
{
|
||||
id: "memberCount",
|
||||
accessorKey: "memberCount",
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title="Members" />
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<span className="font-mono text-sm">{row.original.memberCount}</span>
|
||||
),
|
||||
meta: { label: "Members" },
|
||||
},
|
||||
{
|
||||
id: "createdAt",
|
||||
accessorKey: "createdAt",
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title="Created" />
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-muted-foreground text-sm">
|
||||
{new Date(row.original.createdAt).toLocaleDateString()}
|
||||
</span>
|
||||
),
|
||||
meta: { label: "Created" },
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,43 @@
|
||||
"use client";
|
||||
|
||||
import { use } from "react";
|
||||
|
||||
import { DataTable } from "@turbostarter/ui-web/data-table/data-table";
|
||||
import { DataTableToolbar } from "@turbostarter/ui-web/data-table/data-table-toolbar";
|
||||
|
||||
import { useDataTable } from "~/modules/common/hooks/use-data-table";
|
||||
|
||||
import { useMeshColumns } from "./columns";
|
||||
|
||||
import type { GetMeshesResponse } from "@turbostarter/api/schema";
|
||||
|
||||
interface Props {
|
||||
readonly promise: Promise<Awaited<GetMeshesResponse>>;
|
||||
readonly perPage: number;
|
||||
}
|
||||
|
||||
export const MeshesDataTable = ({ promise, perPage }: Props) => {
|
||||
const columns = useMeshColumns();
|
||||
const { data, total } = use(promise);
|
||||
|
||||
const { table } = useDataTable({
|
||||
persistance: "searchParams",
|
||||
data,
|
||||
columns,
|
||||
pageCount: Math.ceil(total / perPage),
|
||||
initialState: {
|
||||
sorting: [{ id: "createdAt", desc: true }],
|
||||
columnVisibility: { q: false },
|
||||
},
|
||||
shallow: false,
|
||||
clearOnDefault: true,
|
||||
enableRowSelection: false,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex w-full flex-col gap-2">
|
||||
<DataTableToolbar table={table} />
|
||||
<DataTable table={table} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
137
apps/web/src/modules/admin/sessions/data-table/columns.tsx
Normal file
137
apps/web/src/modules/admin/sessions/data-table/columns.tsx
Normal file
@@ -0,0 +1,137 @@
|
||||
import { Badge } from "@turbostarter/ui-web/badge";
|
||||
import { DataTableColumnHeader } from "@turbostarter/ui-web/data-table/data-table-column-header";
|
||||
|
||||
import { TurboLink } from "~/modules/common/turbo-link";
|
||||
|
||||
import type { ColumnDef } from "@tanstack/react-table";
|
||||
import type { GetSessionsResponse } from "@turbostarter/api/schema";
|
||||
|
||||
type Session = GetSessionsResponse["data"][number];
|
||||
|
||||
const STATUS_COLORS: Record<string, string> = {
|
||||
working: "bg-primary/15 text-primary",
|
||||
idle: "bg-muted text-muted-foreground",
|
||||
dnd: "bg-destructive/15 text-destructive",
|
||||
};
|
||||
|
||||
export const useSessionColumns = (): ColumnDef<Session>[] => [
|
||||
{
|
||||
id: "q",
|
||||
accessorKey: "q",
|
||||
meta: { placeholder: "Search by peer, cwd, mesh…", variant: "text" },
|
||||
enableHiding: false,
|
||||
enableColumnFilter: true,
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
accessorKey: "status",
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title="Status" />
|
||||
),
|
||||
cell: ({ row }) => {
|
||||
const disconnected = row.original.disconnectedAt !== null;
|
||||
return (
|
||||
<div className="flex items-center gap-2">
|
||||
<span
|
||||
className={
|
||||
"inline-block h-2 w-2 rounded-full " +
|
||||
(disconnected
|
||||
? "bg-muted-foreground/40"
|
||||
: row.original.status === "working"
|
||||
? "bg-primary animate-pulse"
|
||||
: row.original.status === "dnd"
|
||||
? "bg-destructive"
|
||||
: "bg-muted-foreground")
|
||||
}
|
||||
/>
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className={
|
||||
disconnected
|
||||
? "bg-muted/50 text-muted-foreground"
|
||||
: (STATUS_COLORS[row.original.status] ?? "")
|
||||
}
|
||||
>
|
||||
{disconnected ? "disconnected" : row.original.status}
|
||||
</Badge>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
meta: {
|
||||
label: "Status",
|
||||
variant: "multiSelect",
|
||||
options: [
|
||||
{ label: "Working", value: "working" },
|
||||
{ label: "Idle", value: "idle" },
|
||||
{ label: "DND", value: "dnd" },
|
||||
],
|
||||
},
|
||||
enableColumnFilter: true,
|
||||
},
|
||||
{
|
||||
id: "peer",
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title="Peer" />
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="text-sm font-medium">
|
||||
{row.original.displayName ?? "—"}
|
||||
</span>
|
||||
<span className="text-muted-foreground font-mono text-xs">
|
||||
pid {row.original.pid}
|
||||
</span>
|
||||
</div>
|
||||
),
|
||||
meta: { label: "Peer" },
|
||||
},
|
||||
{
|
||||
id: "mesh",
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title="Mesh" />
|
||||
),
|
||||
cell: ({ row }) =>
|
||||
row.original.meshId ? (
|
||||
<TurboLink
|
||||
href={`/admin/meshes/${row.original.meshId}`}
|
||||
className="group flex flex-col gap-0.5"
|
||||
>
|
||||
<span className="group-hover:text-primary text-sm font-medium underline underline-offset-4">
|
||||
{row.original.meshName ?? "—"}
|
||||
</span>
|
||||
<span className="text-muted-foreground font-mono text-xs">
|
||||
{row.original.meshSlug ?? "—"}
|
||||
</span>
|
||||
</TurboLink>
|
||||
) : (
|
||||
<span className="text-muted-foreground">—</span>
|
||||
),
|
||||
meta: { label: "Mesh" },
|
||||
},
|
||||
{
|
||||
id: "cwd",
|
||||
accessorKey: "cwd",
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title="CWD" />
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<code className="text-muted-foreground max-w-xs truncate text-xs">
|
||||
{row.original.cwd}
|
||||
</code>
|
||||
),
|
||||
meta: { label: "CWD" },
|
||||
},
|
||||
{
|
||||
id: "lastPingAt",
|
||||
accessorKey: "lastPingAt",
|
||||
header: ({ column }) => (
|
||||
<DataTableColumnHeader column={column} title="Last ping" />
|
||||
),
|
||||
cell: ({ row }) => (
|
||||
<span className="text-muted-foreground text-sm">
|
||||
{new Date(row.original.lastPingAt).toLocaleTimeString()}
|
||||
</span>
|
||||
),
|
||||
meta: { label: "Last ping" },
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,43 @@
|
||||
"use client";
|
||||
|
||||
import { use } from "react";
|
||||
|
||||
import { DataTable } from "@turbostarter/ui-web/data-table/data-table";
|
||||
import { DataTableToolbar } from "@turbostarter/ui-web/data-table/data-table-toolbar";
|
||||
|
||||
import { useDataTable } from "~/modules/common/hooks/use-data-table";
|
||||
|
||||
import { useSessionColumns } from "./columns";
|
||||
|
||||
import type { GetSessionsResponse } from "@turbostarter/api/schema";
|
||||
|
||||
interface Props {
|
||||
readonly promise: Promise<Awaited<GetSessionsResponse>>;
|
||||
readonly perPage: number;
|
||||
}
|
||||
|
||||
export const SessionsDataTable = ({ promise, perPage }: Props) => {
|
||||
const columns = useSessionColumns();
|
||||
const { data, total } = use(promise);
|
||||
|
||||
const { table } = useDataTable({
|
||||
persistance: "searchParams",
|
||||
data,
|
||||
columns,
|
||||
pageCount: Math.ceil(total / perPage),
|
||||
initialState: {
|
||||
sorting: [{ id: "lastPingAt", desc: true }],
|
||||
columnVisibility: { q: false },
|
||||
},
|
||||
shallow: false,
|
||||
clearOnDefault: true,
|
||||
enableRowSelection: false,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex w-full flex-col gap-2">
|
||||
<DataTableToolbar table={table} />
|
||||
<DataTable table={table} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -13,6 +13,7 @@
|
||||
"lint:ws": "pnpm dlx sherif@latest -r packages-without-package-json",
|
||||
"prepare": "husky",
|
||||
"auth:seed": "set -a && source apps/web/.env.local && set +a && pnpm --filter @turbostarter/auth db:seed",
|
||||
"admin:grant": "set -a && source apps/web/.env.local && set +a && pnpm --filter @turbostarter/auth admin:grant",
|
||||
"services:logs": "docker compose logs -f",
|
||||
"services:setup": "pnpm services:start && pnpm with-env turbo setup",
|
||||
"services:start": "docker compose up -d --wait",
|
||||
|
||||
89
packages/api/src/modules/admin/audit/queries.ts
Normal file
89
packages/api/src/modules/admin/audit/queries.ts
Normal file
@@ -0,0 +1,89 @@
|
||||
import dayjs from "dayjs";
|
||||
|
||||
import {
|
||||
and,
|
||||
between,
|
||||
count,
|
||||
desc,
|
||||
eq,
|
||||
getOrderByFromSort,
|
||||
gte,
|
||||
ilike,
|
||||
inArray,
|
||||
or,
|
||||
sql,
|
||||
} from "@turbostarter/db";
|
||||
import { auditLog, mesh } from "@turbostarter/db/schema";
|
||||
import { db } from "@turbostarter/db/server";
|
||||
|
||||
import type { GetAuditInput } from "../../../schema";
|
||||
|
||||
export const getMessages24hCount = async () =>
|
||||
db
|
||||
.select({ count: count() })
|
||||
.from(auditLog)
|
||||
.where(
|
||||
and(
|
||||
eq(auditLog.eventType, "message_sent"),
|
||||
gte(auditLog.createdAt, dayjs().subtract(24, "hour").toDate()),
|
||||
),
|
||||
)
|
||||
.then((res) => res[0]?.count ?? 0);
|
||||
|
||||
export const getAudit = async (input: GetAuditInput) => {
|
||||
const offset = (input.page - 1) * input.perPage;
|
||||
|
||||
const where = and(
|
||||
input.q
|
||||
? or(
|
||||
ilike(auditLog.eventType, `%${input.q}%`),
|
||||
ilike(mesh.name, `%${input.q}%`),
|
||||
ilike(auditLog.actorPeerId, `%${input.q}%`),
|
||||
)
|
||||
: undefined,
|
||||
input.eventType ? inArray(auditLog.eventType, input.eventType) : undefined,
|
||||
input.meshId ? inArray(auditLog.meshId, input.meshId) : undefined,
|
||||
input.createdAt
|
||||
? between(
|
||||
auditLog.createdAt,
|
||||
dayjs(input.createdAt[0]).startOf("day").toDate(),
|
||||
dayjs(input.createdAt[1]).endOf("day").toDate(),
|
||||
)
|
||||
: undefined,
|
||||
);
|
||||
|
||||
const orderBy = input.sort
|
||||
? getOrderByFromSort({ sort: input.sort, defaultSchema: auditLog })
|
||||
: [desc(auditLog.createdAt)];
|
||||
|
||||
return db.transaction(async (tx) => {
|
||||
const data = await tx
|
||||
.select({
|
||||
id: auditLog.id,
|
||||
meshId: auditLog.meshId,
|
||||
meshName: mesh.name,
|
||||
meshSlug: mesh.slug,
|
||||
eventType: auditLog.eventType,
|
||||
actorPeerId: auditLog.actorPeerId,
|
||||
targetPeerId: auditLog.targetPeerId,
|
||||
metadata: sql<Record<string, unknown>>`${auditLog.metadata}`,
|
||||
createdAt: auditLog.createdAt,
|
||||
})
|
||||
.from(auditLog)
|
||||
.leftJoin(mesh, eq(auditLog.meshId, mesh.id))
|
||||
.where(where)
|
||||
.limit(input.perPage)
|
||||
.offset(offset)
|
||||
.orderBy(...orderBy);
|
||||
|
||||
const total = await tx
|
||||
.select({ count: count() })
|
||||
.from(auditLog)
|
||||
.leftJoin(mesh, eq(auditLog.meshId, mesh.id))
|
||||
.where(where)
|
||||
.execute()
|
||||
.then((res) => res[0]?.count ?? 0);
|
||||
|
||||
return { data, total };
|
||||
});
|
||||
};
|
||||
12
packages/api/src/modules/admin/audit/router.ts
Normal file
12
packages/api/src/modules/admin/audit/router.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Hono } from "hono";
|
||||
|
||||
import { validate } from "../../../middleware";
|
||||
import { getAuditInputSchema } from "../../../schema";
|
||||
|
||||
import { getAudit } from "./queries";
|
||||
|
||||
export const auditRouter = new Hono().get(
|
||||
"/",
|
||||
validate("query", getAuditInputSchema),
|
||||
async (c) => c.json(await getAudit(c.req.valid("query"))),
|
||||
);
|
||||
73
packages/api/src/modules/admin/invites/queries.ts
Normal file
73
packages/api/src/modules/admin/invites/queries.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import {
|
||||
and,
|
||||
count,
|
||||
desc,
|
||||
eq,
|
||||
getOrderByFromSort,
|
||||
ilike,
|
||||
isNotNull,
|
||||
isNull,
|
||||
lt,
|
||||
or,
|
||||
} from "@turbostarter/db";
|
||||
import { user } from "@turbostarter/db/schema";
|
||||
import { invite, mesh } from "@turbostarter/db/schema";
|
||||
import { db } from "@turbostarter/db/server";
|
||||
|
||||
import type { GetInvitesInput } from "../../../schema";
|
||||
|
||||
export const getInvites = async (input: GetInvitesInput) => {
|
||||
const offset = (input.page - 1) * input.perPage;
|
||||
const now = new Date();
|
||||
|
||||
const where = and(
|
||||
input.q
|
||||
? or(
|
||||
ilike(mesh.name, `%${input.q}%`),
|
||||
ilike(invite.token, `%${input.q}%`),
|
||||
)
|
||||
: undefined,
|
||||
input.revoked === true ? isNotNull(invite.revokedAt) : undefined,
|
||||
input.revoked === false ? isNull(invite.revokedAt) : undefined,
|
||||
input.expired === true ? lt(invite.expiresAt, now) : undefined,
|
||||
);
|
||||
|
||||
const orderBy = input.sort
|
||||
? getOrderByFromSort({ sort: input.sort, defaultSchema: invite })
|
||||
: [desc(invite.createdAt)];
|
||||
|
||||
return db.transaction(async (tx) => {
|
||||
const data = await tx
|
||||
.select({
|
||||
id: invite.id,
|
||||
meshId: invite.meshId,
|
||||
meshName: mesh.name,
|
||||
meshSlug: mesh.slug,
|
||||
token: invite.token,
|
||||
maxUses: invite.maxUses,
|
||||
usedCount: invite.usedCount,
|
||||
role: invite.role,
|
||||
expiresAt: invite.expiresAt,
|
||||
createdAt: invite.createdAt,
|
||||
revokedAt: invite.revokedAt,
|
||||
createdByName: user.name,
|
||||
})
|
||||
.from(invite)
|
||||
.leftJoin(mesh, eq(invite.meshId, mesh.id))
|
||||
.leftJoin(user, eq(invite.createdBy, user.id))
|
||||
.where(where)
|
||||
.limit(input.perPage)
|
||||
.offset(offset)
|
||||
.orderBy(...orderBy);
|
||||
|
||||
const total = await tx
|
||||
.select({ count: count() })
|
||||
.from(invite)
|
||||
.leftJoin(mesh, eq(invite.meshId, mesh.id))
|
||||
.where(where)
|
||||
.execute()
|
||||
.then((res) => res[0]?.count ?? 0);
|
||||
|
||||
return { data, total };
|
||||
});
|
||||
};
|
||||
12
packages/api/src/modules/admin/invites/router.ts
Normal file
12
packages/api/src/modules/admin/invites/router.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Hono } from "hono";
|
||||
|
||||
import { validate } from "../../../middleware";
|
||||
import { getInvitesInputSchema } from "../../../schema";
|
||||
|
||||
import { getInvites } from "./queries";
|
||||
|
||||
export const invitesRouter = new Hono().get(
|
||||
"/",
|
||||
validate("query", getInvitesInputSchema),
|
||||
async (c) => c.json(await getInvites(c.req.valid("query"))),
|
||||
);
|
||||
195
packages/api/src/modules/admin/meshes/queries.ts
Normal file
195
packages/api/src/modules/admin/meshes/queries.ts
Normal file
@@ -0,0 +1,195 @@
|
||||
import dayjs from "dayjs";
|
||||
|
||||
import {
|
||||
and,
|
||||
asc,
|
||||
between,
|
||||
count,
|
||||
desc,
|
||||
eq,
|
||||
getOrderByFromSort,
|
||||
ilike,
|
||||
inArray,
|
||||
isNull,
|
||||
isNotNull,
|
||||
or,
|
||||
sql,
|
||||
} from "@turbostarter/db";
|
||||
import { user } from "@turbostarter/db/schema";
|
||||
import {
|
||||
auditLog,
|
||||
invite,
|
||||
mesh,
|
||||
meshMember,
|
||||
presence,
|
||||
} from "@turbostarter/db/schema";
|
||||
import { db } from "@turbostarter/db/server";
|
||||
|
||||
import type { GetMeshesInput } from "../../../schema";
|
||||
|
||||
export const getMeshesCount = async () =>
|
||||
db
|
||||
.select({ count: count() })
|
||||
.from(mesh)
|
||||
.then((res) => res[0]?.count ?? 0);
|
||||
|
||||
export const getActiveMeshesCount = async () =>
|
||||
db
|
||||
.select({ count: count() })
|
||||
.from(mesh)
|
||||
.where(isNull(mesh.archivedAt))
|
||||
.then((res) => res[0]?.count ?? 0);
|
||||
|
||||
export const getMeshes = async (input: GetMeshesInput) => {
|
||||
const offset = (input.page - 1) * input.perPage;
|
||||
|
||||
const where = and(
|
||||
input.q
|
||||
? or(ilike(mesh.name, `%${input.q}%`), ilike(mesh.slug, `%${input.q}%`))
|
||||
: undefined,
|
||||
input.tier ? inArray(mesh.tier, input.tier) : undefined,
|
||||
input.transport ? inArray(mesh.transport, input.transport) : undefined,
|
||||
input.visibility ? inArray(mesh.visibility, input.visibility) : undefined,
|
||||
input.archived === true ? isNotNull(mesh.archivedAt) : undefined,
|
||||
input.archived === false ? isNull(mesh.archivedAt) : undefined,
|
||||
input.createdAt
|
||||
? between(
|
||||
mesh.createdAt,
|
||||
dayjs(input.createdAt[0]).startOf("day").toDate(),
|
||||
dayjs(input.createdAt[1]).endOf("day").toDate(),
|
||||
)
|
||||
: undefined,
|
||||
);
|
||||
|
||||
const orderBy = input.sort
|
||||
? getOrderByFromSort({ sort: input.sort, defaultSchema: mesh })
|
||||
: [desc(mesh.createdAt)];
|
||||
|
||||
return db.transaction(async (tx) => {
|
||||
const data = await tx
|
||||
.select({
|
||||
id: mesh.id,
|
||||
name: mesh.name,
|
||||
slug: mesh.slug,
|
||||
visibility: mesh.visibility,
|
||||
transport: mesh.transport,
|
||||
tier: mesh.tier,
|
||||
maxPeers: mesh.maxPeers,
|
||||
createdAt: mesh.createdAt,
|
||||
archivedAt: mesh.archivedAt,
|
||||
ownerUserId: mesh.ownerUserId,
|
||||
ownerName: user.name,
|
||||
ownerEmail: user.email,
|
||||
memberCount: sql<number>`(
|
||||
SELECT COUNT(*)::int FROM mesh.member m WHERE m.mesh_id = ${mesh.id}
|
||||
)`,
|
||||
})
|
||||
.from(mesh)
|
||||
.leftJoin(user, eq(mesh.ownerUserId, user.id))
|
||||
.where(where)
|
||||
.limit(input.perPage)
|
||||
.offset(offset)
|
||||
.orderBy(...orderBy);
|
||||
|
||||
const total = await tx
|
||||
.select({ count: count() })
|
||||
.from(mesh)
|
||||
.where(where)
|
||||
.execute()
|
||||
.then((res) => res[0]?.count ?? 0);
|
||||
|
||||
return { data, total };
|
||||
});
|
||||
};
|
||||
|
||||
export const getMeshById = async (id: string) => {
|
||||
const [m] = await db
|
||||
.select({
|
||||
id: mesh.id,
|
||||
name: mesh.name,
|
||||
slug: mesh.slug,
|
||||
visibility: mesh.visibility,
|
||||
transport: mesh.transport,
|
||||
tier: mesh.tier,
|
||||
maxPeers: mesh.maxPeers,
|
||||
createdAt: mesh.createdAt,
|
||||
archivedAt: mesh.archivedAt,
|
||||
ownerUserId: mesh.ownerUserId,
|
||||
ownerName: user.name,
|
||||
ownerEmail: user.email,
|
||||
})
|
||||
.from(mesh)
|
||||
.leftJoin(user, eq(mesh.ownerUserId, user.id))
|
||||
.where(eq(mesh.id, id))
|
||||
.limit(1);
|
||||
|
||||
if (!m) return null;
|
||||
|
||||
const members = await db
|
||||
.select({
|
||||
id: meshMember.id,
|
||||
displayName: meshMember.displayName,
|
||||
peerPubkey: meshMember.peerPubkey,
|
||||
role: meshMember.role,
|
||||
joinedAt: meshMember.joinedAt,
|
||||
lastSeenAt: meshMember.lastSeenAt,
|
||||
revokedAt: meshMember.revokedAt,
|
||||
userId: meshMember.userId,
|
||||
})
|
||||
.from(meshMember)
|
||||
.where(eq(meshMember.meshId, id))
|
||||
.orderBy(asc(meshMember.joinedAt));
|
||||
|
||||
const presences = await db
|
||||
.select({
|
||||
id: presence.id,
|
||||
memberId: presence.memberId,
|
||||
displayName: meshMember.displayName,
|
||||
sessionId: presence.sessionId,
|
||||
pid: presence.pid,
|
||||
cwd: presence.cwd,
|
||||
status: presence.status,
|
||||
statusSource: presence.statusSource,
|
||||
statusUpdatedAt: presence.statusUpdatedAt,
|
||||
connectedAt: presence.connectedAt,
|
||||
lastPingAt: presence.lastPingAt,
|
||||
disconnectedAt: presence.disconnectedAt,
|
||||
})
|
||||
.from(presence)
|
||||
.leftJoin(meshMember, eq(presence.memberId, meshMember.id))
|
||||
.where(eq(meshMember.meshId, id))
|
||||
.orderBy(desc(presence.connectedAt))
|
||||
.limit(50);
|
||||
|
||||
const invites = await db
|
||||
.select({
|
||||
id: invite.id,
|
||||
token: invite.token,
|
||||
maxUses: invite.maxUses,
|
||||
usedCount: invite.usedCount,
|
||||
role: invite.role,
|
||||
expiresAt: invite.expiresAt,
|
||||
createdAt: invite.createdAt,
|
||||
revokedAt: invite.revokedAt,
|
||||
})
|
||||
.from(invite)
|
||||
.where(eq(invite.meshId, id))
|
||||
.orderBy(desc(invite.createdAt))
|
||||
.limit(50);
|
||||
|
||||
const auditEvents = await db
|
||||
.select({
|
||||
id: auditLog.id,
|
||||
eventType: auditLog.eventType,
|
||||
actorPeerId: auditLog.actorPeerId,
|
||||
targetPeerId: auditLog.targetPeerId,
|
||||
metadata: auditLog.metadata,
|
||||
createdAt: auditLog.createdAt,
|
||||
})
|
||||
.from(auditLog)
|
||||
.where(eq(auditLog.meshId, id))
|
||||
.orderBy(desc(auditLog.createdAt))
|
||||
.limit(50);
|
||||
|
||||
return { mesh: m, members, presences, invites, auditEvents };
|
||||
};
|
||||
22
packages/api/src/modules/admin/meshes/router.ts
Normal file
22
packages/api/src/modules/admin/meshes/router.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { Hono } from "hono";
|
||||
|
||||
import { validate } from "../../../middleware";
|
||||
import { getMeshesInputSchema } from "../../../schema";
|
||||
|
||||
import { getMeshById, getMeshes } from "./queries";
|
||||
|
||||
export const meshesRouter = new Hono()
|
||||
.get("/", validate("query", getMeshesInputSchema), async (c) =>
|
||||
c.json(await getMeshes(c.req.valid("query"))),
|
||||
)
|
||||
.get("/:id", async (c) =>
|
||||
c.json(
|
||||
(await getMeshById(c.req.param("id"))) ?? {
|
||||
mesh: null,
|
||||
members: [],
|
||||
presences: [],
|
||||
invites: [],
|
||||
auditEvents: [],
|
||||
},
|
||||
),
|
||||
);
|
||||
@@ -2,10 +2,23 @@ import { Hono } from "hono";
|
||||
|
||||
import { enforceAdmin, enforceAuth } from "../../middleware";
|
||||
|
||||
import { auditRouter } from "./audit/router";
|
||||
import { getMessages24hCount } from "./audit/queries";
|
||||
import { getCustomersCount } from "./customers/queries";
|
||||
import { customersRouter } from "./customers/router";
|
||||
import { invitesRouter } from "./invites/router";
|
||||
import {
|
||||
getActiveMeshesCount,
|
||||
getMeshesCount,
|
||||
} from "./meshes/queries";
|
||||
import { meshesRouter } from "./meshes/router";
|
||||
import { getOrganizationsCount } from "./organizations/queries";
|
||||
import { organizationsRouter } from "./organizations/router";
|
||||
import {
|
||||
getActivePresencesCount,
|
||||
getPresencesCount,
|
||||
} from "./sessions/queries";
|
||||
import { sessionsRouter } from "./sessions/router";
|
||||
import { getUsersCount } from "./users/queries";
|
||||
import { usersRouter } from "./users/router";
|
||||
|
||||
@@ -15,6 +28,10 @@ export const adminRouter = new Hono()
|
||||
.route("/users", usersRouter)
|
||||
.route("/organizations", organizationsRouter)
|
||||
.route("/customers", customersRouter)
|
||||
.route("/meshes", meshesRouter)
|
||||
.route("/sessions", sessionsRouter)
|
||||
.route("/invites", invitesRouter)
|
||||
.route("/audit", auditRouter)
|
||||
.get("/summary", async (c) => {
|
||||
const [users, organizations, customers] = await Promise.all([
|
||||
getUsersCount(),
|
||||
@@ -23,4 +40,22 @@ export const adminRouter = new Hono()
|
||||
]);
|
||||
|
||||
return c.json({ users, organizations, customers });
|
||||
})
|
||||
.get("/summary/mesh", async (c) => {
|
||||
const [meshes, activeMeshes, totalPresences, activePresences, messages24h] =
|
||||
await Promise.all([
|
||||
getMeshesCount(),
|
||||
getActiveMeshesCount(),
|
||||
getPresencesCount(),
|
||||
getActivePresencesCount(),
|
||||
getMessages24hCount(),
|
||||
]);
|
||||
|
||||
return c.json({
|
||||
meshes,
|
||||
activeMeshes,
|
||||
totalPresences,
|
||||
activePresences,
|
||||
messages24h,
|
||||
});
|
||||
});
|
||||
|
||||
91
packages/api/src/modules/admin/sessions/queries.ts
Normal file
91
packages/api/src/modules/admin/sessions/queries.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
import {
|
||||
and,
|
||||
count,
|
||||
desc,
|
||||
eq,
|
||||
getOrderByFromSort,
|
||||
ilike,
|
||||
inArray,
|
||||
isNull,
|
||||
or,
|
||||
sql,
|
||||
} from "@turbostarter/db";
|
||||
import { mesh, meshMember, presence } from "@turbostarter/db/schema";
|
||||
import { db } from "@turbostarter/db/server";
|
||||
|
||||
import type { GetSessionsInput } from "../../../schema";
|
||||
|
||||
export const getPresencesCount = async () =>
|
||||
db
|
||||
.select({ count: count() })
|
||||
.from(presence)
|
||||
.then((res) => res[0]?.count ?? 0);
|
||||
|
||||
export const getActivePresencesCount = async () =>
|
||||
db
|
||||
.select({ count: count() })
|
||||
.from(presence)
|
||||
.where(isNull(presence.disconnectedAt))
|
||||
.then((res) => res[0]?.count ?? 0);
|
||||
|
||||
export const getSessions = async (input: GetSessionsInput) => {
|
||||
const offset = (input.page - 1) * input.perPage;
|
||||
|
||||
const where = and(
|
||||
input.q
|
||||
? or(
|
||||
ilike(meshMember.displayName, `%${input.q}%`),
|
||||
ilike(presence.cwd, `%${input.q}%`),
|
||||
ilike(mesh.name, `%${input.q}%`),
|
||||
)
|
||||
: undefined,
|
||||
input.status ? inArray(presence.status, input.status) : undefined,
|
||||
input.active === true ? isNull(presence.disconnectedAt) : undefined,
|
||||
input.active === false
|
||||
? sql`${presence.disconnectedAt} IS NOT NULL`
|
||||
: undefined,
|
||||
);
|
||||
|
||||
const orderBy = input.sort
|
||||
? getOrderByFromSort({ sort: input.sort, defaultSchema: presence })
|
||||
: [desc(presence.lastPingAt)];
|
||||
|
||||
return db.transaction(async (tx) => {
|
||||
const data = await tx
|
||||
.select({
|
||||
id: presence.id,
|
||||
memberId: presence.memberId,
|
||||
displayName: meshMember.displayName,
|
||||
meshId: meshMember.meshId,
|
||||
meshName: mesh.name,
|
||||
meshSlug: mesh.slug,
|
||||
sessionId: presence.sessionId,
|
||||
pid: presence.pid,
|
||||
cwd: presence.cwd,
|
||||
status: presence.status,
|
||||
statusSource: presence.statusSource,
|
||||
statusUpdatedAt: presence.statusUpdatedAt,
|
||||
connectedAt: presence.connectedAt,
|
||||
lastPingAt: presence.lastPingAt,
|
||||
disconnectedAt: presence.disconnectedAt,
|
||||
})
|
||||
.from(presence)
|
||||
.leftJoin(meshMember, eq(presence.memberId, meshMember.id))
|
||||
.leftJoin(mesh, eq(meshMember.meshId, mesh.id))
|
||||
.where(where)
|
||||
.limit(input.perPage)
|
||||
.offset(offset)
|
||||
.orderBy(...orderBy);
|
||||
|
||||
const total = await tx
|
||||
.select({ count: count() })
|
||||
.from(presence)
|
||||
.leftJoin(meshMember, eq(presence.memberId, meshMember.id))
|
||||
.leftJoin(mesh, eq(meshMember.meshId, mesh.id))
|
||||
.where(where)
|
||||
.execute()
|
||||
.then((res) => res[0]?.count ?? 0);
|
||||
|
||||
return { data, total };
|
||||
});
|
||||
};
|
||||
12
packages/api/src/modules/admin/sessions/router.ts
Normal file
12
packages/api/src/modules/admin/sessions/router.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Hono } from "hono";
|
||||
|
||||
import { validate } from "../../../middleware";
|
||||
import { getSessionsInputSchema } from "../../../schema";
|
||||
|
||||
import { getSessions } from "./queries";
|
||||
|
||||
export const sessionsRouter = new Hono().get(
|
||||
"/",
|
||||
validate("query", getSessionsInputSchema),
|
||||
async (c) => c.json(await getSessions(c.req.valid("query"))),
|
||||
);
|
||||
@@ -1,2 +1,3 @@
|
||||
export * from "./admin";
|
||||
export * from "./mesh-admin";
|
||||
export * from "./organization";
|
||||
|
||||
274
packages/api/src/schema/mesh-admin.ts
Normal file
274
packages/api/src/schema/mesh-admin.ts
Normal file
@@ -0,0 +1,274 @@
|
||||
import * as z from "zod";
|
||||
|
||||
import {
|
||||
offsetPaginationSchema,
|
||||
sortSchema,
|
||||
} from "@turbostarter/shared/schema";
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Meshes
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
export const meshTierEnum = z.enum(["free", "pro", "team", "enterprise"]);
|
||||
export const meshTransportEnum = z.enum([
|
||||
"managed",
|
||||
"tailscale",
|
||||
"self_hosted",
|
||||
]);
|
||||
export const meshVisibilityEnum = z.enum(["private", "public"]);
|
||||
|
||||
export const getMeshesInputSchema = offsetPaginationSchema.extend({
|
||||
sort: z
|
||||
.string()
|
||||
.transform((val) =>
|
||||
z.array(sortSchema).parse(JSON.parse(decodeURIComponent(val))),
|
||||
)
|
||||
.optional(),
|
||||
q: z.string().optional(),
|
||||
tier: z
|
||||
.union([meshTierEnum.transform((v) => [v]), z.array(meshTierEnum)])
|
||||
.optional(),
|
||||
transport: z
|
||||
.union([
|
||||
meshTransportEnum.transform((v) => [v]),
|
||||
z.array(meshTransportEnum),
|
||||
])
|
||||
.optional(),
|
||||
visibility: z
|
||||
.union([
|
||||
meshVisibilityEnum.transform((v) => [v]),
|
||||
z.array(meshVisibilityEnum),
|
||||
])
|
||||
.optional(),
|
||||
archived: z.coerce.boolean().optional(),
|
||||
createdAt: z.tuple([z.coerce.number(), z.coerce.number()]).optional(),
|
||||
});
|
||||
export type GetMeshesInput = z.infer<typeof getMeshesInputSchema>;
|
||||
|
||||
export const getMeshesResponseSchema = z.object({
|
||||
data: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
slug: z.string(),
|
||||
visibility: meshVisibilityEnum,
|
||||
transport: meshTransportEnum,
|
||||
tier: meshTierEnum,
|
||||
maxPeers: z.number().nullable(),
|
||||
createdAt: z.coerce.date(),
|
||||
archivedAt: z.coerce.date().nullable(),
|
||||
ownerUserId: z.string(),
|
||||
ownerName: z.string().nullable(),
|
||||
ownerEmail: z.string().nullable(),
|
||||
memberCount: z.number(),
|
||||
}),
|
||||
),
|
||||
total: z.number(),
|
||||
});
|
||||
export type GetMeshesResponse = z.infer<typeof getMeshesResponseSchema>;
|
||||
|
||||
export const getMeshResponseSchema = z.object({
|
||||
mesh: z
|
||||
.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
slug: z.string(),
|
||||
visibility: meshVisibilityEnum,
|
||||
transport: meshTransportEnum,
|
||||
tier: meshTierEnum,
|
||||
maxPeers: z.number().nullable(),
|
||||
createdAt: z.coerce.date(),
|
||||
archivedAt: z.coerce.date().nullable(),
|
||||
ownerUserId: z.string(),
|
||||
ownerName: z.string().nullable(),
|
||||
ownerEmail: z.string().nullable(),
|
||||
})
|
||||
.nullable(),
|
||||
members: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
displayName: z.string(),
|
||||
peerPubkey: z.string(),
|
||||
role: z.enum(["admin", "member"]),
|
||||
joinedAt: z.coerce.date(),
|
||||
lastSeenAt: z.coerce.date().nullable(),
|
||||
revokedAt: z.coerce.date().nullable(),
|
||||
userId: z.string().nullable(),
|
||||
}),
|
||||
),
|
||||
presences: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
memberId: z.string(),
|
||||
displayName: z.string().nullable(),
|
||||
sessionId: z.string(),
|
||||
pid: z.number(),
|
||||
cwd: z.string(),
|
||||
status: z.enum(["idle", "working", "dnd"]),
|
||||
statusSource: z.enum(["hook", "manual", "jsonl"]),
|
||||
statusUpdatedAt: z.coerce.date(),
|
||||
connectedAt: z.coerce.date(),
|
||||
lastPingAt: z.coerce.date(),
|
||||
disconnectedAt: z.coerce.date().nullable(),
|
||||
}),
|
||||
),
|
||||
invites: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
token: z.string(),
|
||||
maxUses: z.number(),
|
||||
usedCount: z.number(),
|
||||
role: z.enum(["admin", "member"]),
|
||||
expiresAt: z.coerce.date(),
|
||||
createdAt: z.coerce.date(),
|
||||
revokedAt: z.coerce.date().nullable(),
|
||||
}),
|
||||
),
|
||||
auditEvents: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
eventType: z.string(),
|
||||
actorPeerId: z.string().nullable(),
|
||||
targetPeerId: z.string().nullable(),
|
||||
metadata: z.record(z.string(), z.any()),
|
||||
createdAt: z.coerce.date(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
export type GetMeshResponse = z.infer<typeof getMeshResponseSchema>;
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Sessions (live presences across all meshes)
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
export const presenceStatusEnum = z.enum(["idle", "working", "dnd"]);
|
||||
|
||||
export const getSessionsInputSchema = offsetPaginationSchema.extend({
|
||||
sort: z
|
||||
.string()
|
||||
.transform((val) =>
|
||||
z.array(sortSchema).parse(JSON.parse(decodeURIComponent(val))),
|
||||
)
|
||||
.optional(),
|
||||
q: z.string().optional(),
|
||||
status: z
|
||||
.union([presenceStatusEnum.transform((v) => [v]), z.array(presenceStatusEnum)])
|
||||
.optional(),
|
||||
active: z.coerce.boolean().optional(),
|
||||
});
|
||||
export type GetSessionsInput = z.infer<typeof getSessionsInputSchema>;
|
||||
|
||||
export const getSessionsResponseSchema = z.object({
|
||||
data: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
memberId: z.string(),
|
||||
displayName: z.string().nullable(),
|
||||
meshId: z.string(),
|
||||
meshName: z.string().nullable(),
|
||||
meshSlug: z.string().nullable(),
|
||||
sessionId: z.string(),
|
||||
pid: z.number(),
|
||||
cwd: z.string(),
|
||||
status: presenceStatusEnum,
|
||||
statusSource: z.enum(["hook", "manual", "jsonl"]),
|
||||
statusUpdatedAt: z.coerce.date(),
|
||||
connectedAt: z.coerce.date(),
|
||||
lastPingAt: z.coerce.date(),
|
||||
disconnectedAt: z.coerce.date().nullable(),
|
||||
}),
|
||||
),
|
||||
total: z.number(),
|
||||
});
|
||||
export type GetSessionsResponse = z.infer<typeof getSessionsResponseSchema>;
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Invites
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
export const getInvitesInputSchema = offsetPaginationSchema.extend({
|
||||
sort: z
|
||||
.string()
|
||||
.transform((val) =>
|
||||
z.array(sortSchema).parse(JSON.parse(decodeURIComponent(val))),
|
||||
)
|
||||
.optional(),
|
||||
q: z.string().optional(),
|
||||
revoked: z.coerce.boolean().optional(),
|
||||
expired: z.coerce.boolean().optional(),
|
||||
});
|
||||
export type GetInvitesInput = z.infer<typeof getInvitesInputSchema>;
|
||||
|
||||
export const getInvitesResponseSchema = z.object({
|
||||
data: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
meshId: z.string(),
|
||||
meshName: z.string().nullable(),
|
||||
meshSlug: z.string().nullable(),
|
||||
token: z.string(),
|
||||
maxUses: z.number(),
|
||||
usedCount: z.number(),
|
||||
role: z.enum(["admin", "member"]),
|
||||
expiresAt: z.coerce.date(),
|
||||
createdAt: z.coerce.date(),
|
||||
revokedAt: z.coerce.date().nullable(),
|
||||
createdByName: z.string().nullable(),
|
||||
}),
|
||||
),
|
||||
total: z.number(),
|
||||
});
|
||||
export type GetInvitesResponse = z.infer<typeof getInvitesResponseSchema>;
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Audit log
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
export const getAuditInputSchema = offsetPaginationSchema.extend({
|
||||
sort: z
|
||||
.string()
|
||||
.transform((val) =>
|
||||
z.array(sortSchema).parse(JSON.parse(decodeURIComponent(val))),
|
||||
)
|
||||
.optional(),
|
||||
q: z.string().optional(),
|
||||
eventType: z
|
||||
.union([z.string().transform((v) => [v]), z.array(z.string())])
|
||||
.optional(),
|
||||
meshId: z
|
||||
.union([z.string().transform((v) => [v]), z.array(z.string())])
|
||||
.optional(),
|
||||
createdAt: z.tuple([z.coerce.number(), z.coerce.number()]).optional(),
|
||||
});
|
||||
export type GetAuditInput = z.infer<typeof getAuditInputSchema>;
|
||||
|
||||
export const getAuditResponseSchema = z.object({
|
||||
data: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
meshId: z.string(),
|
||||
meshName: z.string().nullable(),
|
||||
meshSlug: z.string().nullable(),
|
||||
eventType: z.string(),
|
||||
actorPeerId: z.string().nullable(),
|
||||
targetPeerId: z.string().nullable(),
|
||||
metadata: z.record(z.string(), z.any()),
|
||||
createdAt: z.coerce.date(),
|
||||
}),
|
||||
),
|
||||
total: z.number(),
|
||||
});
|
||||
export type GetAuditResponse = z.infer<typeof getAuditResponseSchema>;
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// Summary counts
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
export const getMeshSummaryResponseSchema = z.object({
|
||||
meshes: z.number(),
|
||||
activeMeshes: z.number(),
|
||||
totalPresences: z.number(),
|
||||
activePresences: z.number(),
|
||||
messages24h: z.number(),
|
||||
});
|
||||
export type GetMeshSummaryResponse = z.infer<typeof getMeshSummaryResponseSchema>;
|
||||
@@ -13,6 +13,7 @@
|
||||
"clean": "git clean -xdf .cache .turbo dist node_modules",
|
||||
"db:generate": "cross-env SKIP_ENV_VALIDATION=1 pnpm dlx @better-auth/cli@1.4.3 generate --config src/server.ts --output ../db/src/schema/auth.ts --y",
|
||||
"db:seed": "cross-env SKIP_ENV_VALIDATION=1 pnpm dlx tsx ./src/scripts/seed.ts",
|
||||
"admin:grant": "cross-env SKIP_ENV_VALIDATION=1 pnpm dlx tsx ./src/scripts/grant-admin.ts",
|
||||
"format": "prettier --check . --ignore-path ../../.gitignore",
|
||||
"lint": "eslint",
|
||||
"test": "vitest run",
|
||||
|
||||
44
packages/auth/src/scripts/grant-admin.ts
Normal file
44
packages/auth/src/scripts/grant-admin.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* Grants admin privileges to a user by email.
|
||||
*
|
||||
* Usage:
|
||||
* pnpm admin:grant <email>
|
||||
*
|
||||
* Resolved via packages/auth/package.json → root package.json alias.
|
||||
* Flips user.role to "admin" via BetterAuth's admin plugin convention
|
||||
* (role column, not a custom isAdmin boolean).
|
||||
*/
|
||||
import { eq } from "@turbostarter/db";
|
||||
import * as schema from "@turbostarter/db/schema";
|
||||
import { db } from "@turbostarter/db/server";
|
||||
import { logger } from "@turbostarter/shared/logger";
|
||||
|
||||
import { UserRole } from "../types";
|
||||
|
||||
const email = process.argv[2];
|
||||
|
||||
if (!email) {
|
||||
logger.error("Usage: pnpm admin:grant <email>");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const rows = await db
|
||||
.update(schema.user)
|
||||
.set({ role: UserRole.ADMIN })
|
||||
.where(eq(schema.user.email, email))
|
||||
.returning({
|
||||
id: schema.user.id,
|
||||
email: schema.user.email,
|
||||
role: schema.user.role,
|
||||
});
|
||||
|
||||
if (rows.length === 0) {
|
||||
logger.error(`No user found with email: ${email}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const updated = rows[0]!;
|
||||
logger.info(
|
||||
`✓ Granted admin to ${updated.email} (id: ${updated.id}, role: ${updated.role})`,
|
||||
);
|
||||
process.exit(0);
|
||||
Reference in New Issue
Block a user