-
+
minmon
diff --git a/apps/web/src/components/mode-toggle.tsx b/apps/web/src/components/mode-toggle.tsx
index e986716..7f06420 100644
--- a/apps/web/src/components/mode-toggle.tsx
+++ b/apps/web/src/components/mode-toggle.tsx
@@ -15,14 +15,20 @@ export function ModeToggle() {
return (
}>
-
-
+
+
Toggle theme
- setTheme("light")}>Light
- setTheme("dark")}>Dark
- setTheme("system")}>System
+ setTheme("light")}>
+ Light
+
+ setTheme("dark")}>
+ Dark
+
+ setTheme("system")}>
+ System
+
);
diff --git a/apps/web/src/components/sign-in-form.tsx b/apps/web/src/components/sign-in-form.tsx
index 352a4df..1642554 100644
--- a/apps/web/src/components/sign-in-form.tsx
+++ b/apps/web/src/components/sign-in-form.tsx
@@ -56,10 +56,12 @@ export default function SignInForm() {
-
Admin Access
+
+ Private access
+
Sign in
- Use your administrator account to open the protected monitoring dashboard.
+ Use your Minmon account to open the protected monitoring dashboard.
@@ -105,7 +107,10 @@ export default function SignInForm() {
({ canSubmit: state.canSubmit, isSubmitting: state.isSubmitting })}
+ selector={(state) => ({
+ canSubmit: state.canSubmit,
+ isSubmitting: state.isSubmitting,
+ })}
>
{({ canSubmit, isSubmitting }) => (
-
Student demo flow uses administrator sign-in only.
+
+ Accounts are created by an administrator or through a one-time
+ invitation.
+
diff --git a/apps/web/src/components/user-menu.tsx b/apps/web/src/components/user-menu.tsx
index f7792d9..c42ac24 100644
--- a/apps/web/src/components/user-menu.tsx
+++ b/apps/web/src/components/user-menu.tsx
@@ -23,9 +23,13 @@ export default function UserMenu() {
if (!session) {
return (
-
-
Sign In
-
+
}
+ nativeButton={false}
+ >
+ Sign In
+
);
}
diff --git a/apps/web/src/lib/auth-client.ts b/apps/web/src/lib/auth-client.ts
index 04a0c88..7965f69 100644
--- a/apps/web/src/lib/auth-client.ts
+++ b/apps/web/src/lib/auth-client.ts
@@ -1,6 +1,19 @@
import { env } from "@minmon/env/web";
+import { inferAdditionalFields } from "better-auth/client/plugins";
import { createAuthClient } from "better-auth/react";
export const authClient = createAuthClient({
baseURL: env.VITE_SERVER_URL,
+ plugins: [
+ inferAdditionalFields({
+ user: {
+ mustChangePassword: {
+ type: "boolean",
+ required: false,
+ defaultValue: false,
+ input: false,
+ },
+ },
+ }),
+ ],
});
diff --git a/apps/web/src/lib/protected-route.ts b/apps/web/src/lib/protected-route.ts
index f21d9f9..f2ea8e9 100644
--- a/apps/web/src/lib/protected-route.ts
+++ b/apps/web/src/lib/protected-route.ts
@@ -6,9 +6,32 @@ export async function requireSession() {
const session = await authClient.getSession();
if (!session.data) {
- redirect({
+ throw redirect({
to: "/login",
- throw: true,
+ });
+ }
+
+ if (session.data.user.mustChangePassword) {
+ throw redirect({
+ to: "/change-password",
+ });
+ }
+
+ return { session };
+}
+
+export async function requireInitialPasswordChange() {
+ const session = await authClient.getSession();
+
+ if (!session.data) {
+ throw redirect({
+ to: "/login",
+ });
+ }
+
+ if (!session.data.user.mustChangePassword) {
+ throw redirect({
+ to: "/dashboard",
});
}
diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts
index 7eeb976..553feb3 100644
--- a/apps/web/src/routeTree.gen.ts
+++ b/apps/web/src/routeTree.gen.ts
@@ -9,10 +9,13 @@
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
import { Route as rootRouteImport } from './routes/__root'
+import { Route as SetupRouteImport } from './routes/setup'
import { Route as LoginRouteImport } from './routes/login'
import { Route as DashboardRouteImport } from './routes/dashboard'
+import { Route as ChangePasswordRouteImport } from './routes/change-password'
import { Route as IndexRouteImport } from './routes/index'
import { Route as DashboardIndexRouteImport } from './routes/dashboard.index'
+import { Route as InviteTokenRouteImport } from './routes/invite.$token'
import { Route as DashboardUsersRouteImport } from './routes/dashboard.users'
import { Route as DashboardServicesRouteImport } from './routes/dashboard.services'
import { Route as DashboardServersRouteImport } from './routes/dashboard.servers'
@@ -27,6 +30,11 @@ import { Route as DashboardNotesNoteIdRouteImport } from './routes/dashboard.not
import { Route as DashboardDomainsNewRouteImport } from './routes/dashboard.domains_.new'
import { Route as DashboardDomainsDomainIdRouteImport } from './routes/dashboard.domains_.$domainId'
+const SetupRoute = SetupRouteImport.update({
+ id: '/setup',
+ path: '/setup',
+ getParentRoute: () => rootRouteImport,
+} as any)
const LoginRoute = LoginRouteImport.update({
id: '/login',
path: '/login',
@@ -37,6 +45,11 @@ const DashboardRoute = DashboardRouteImport.update({
path: '/dashboard',
getParentRoute: () => rootRouteImport,
} as any)
+const ChangePasswordRoute = ChangePasswordRouteImport.update({
+ id: '/change-password',
+ path: '/change-password',
+ getParentRoute: () => rootRouteImport,
+} as any)
const IndexRoute = IndexRouteImport.update({
id: '/',
path: '/',
@@ -47,6 +60,11 @@ const DashboardIndexRoute = DashboardIndexRouteImport.update({
path: '/',
getParentRoute: () => DashboardRoute,
} as any)
+const InviteTokenRoute = InviteTokenRouteImport.update({
+ id: '/invite/$token',
+ path: '/invite/$token',
+ getParentRoute: () => rootRouteImport,
+} as any)
const DashboardUsersRoute = DashboardUsersRouteImport.update({
id: '/users',
path: '/users',
@@ -118,13 +136,16 @@ const DashboardDomainsDomainIdRoute =
export interface FileRoutesByFullPath {
'/': typeof IndexRoute
+ '/change-password': typeof ChangePasswordRoute
'/dashboard': typeof DashboardRouteWithChildren
'/login': typeof LoginRoute
+ '/setup': typeof SetupRoute
'/dashboard/domains': typeof DashboardDomainsRoute
'/dashboard/notes': typeof DashboardNotesRoute
'/dashboard/servers': typeof DashboardServersRoute
'/dashboard/services': typeof DashboardServicesRoute
'/dashboard/users': typeof DashboardUsersRoute
+ '/invite/$token': typeof InviteTokenRoute
'/dashboard/': typeof DashboardIndexRoute
'/dashboard/domains/$domainId': typeof DashboardDomainsDomainIdRoute
'/dashboard/domains/new': typeof DashboardDomainsNewRoute
@@ -137,12 +158,15 @@ export interface FileRoutesByFullPath {
}
export interface FileRoutesByTo {
'/': typeof IndexRoute
+ '/change-password': typeof ChangePasswordRoute
'/login': typeof LoginRoute
+ '/setup': typeof SetupRoute
'/dashboard/domains': typeof DashboardDomainsRoute
'/dashboard/notes': typeof DashboardNotesRoute
'/dashboard/servers': typeof DashboardServersRoute
'/dashboard/services': typeof DashboardServicesRoute
'/dashboard/users': typeof DashboardUsersRoute
+ '/invite/$token': typeof InviteTokenRoute
'/dashboard': typeof DashboardIndexRoute
'/dashboard/domains/$domainId': typeof DashboardDomainsDomainIdRoute
'/dashboard/domains/new': typeof DashboardDomainsNewRoute
@@ -156,13 +180,16 @@ export interface FileRoutesByTo {
export interface FileRoutesById {
__root__: typeof rootRouteImport
'/': typeof IndexRoute
+ '/change-password': typeof ChangePasswordRoute
'/dashboard': typeof DashboardRouteWithChildren
'/login': typeof LoginRoute
+ '/setup': typeof SetupRoute
'/dashboard/domains': typeof DashboardDomainsRoute
'/dashboard/notes': typeof DashboardNotesRoute
'/dashboard/servers': typeof DashboardServersRoute
'/dashboard/services': typeof DashboardServicesRoute
'/dashboard/users': typeof DashboardUsersRoute
+ '/invite/$token': typeof InviteTokenRoute
'/dashboard/': typeof DashboardIndexRoute
'/dashboard/domains_/$domainId': typeof DashboardDomainsDomainIdRoute
'/dashboard/domains_/new': typeof DashboardDomainsNewRoute
@@ -177,13 +204,16 @@ export interface FileRouteTypes {
fileRoutesByFullPath: FileRoutesByFullPath
fullPaths:
| '/'
+ | '/change-password'
| '/dashboard'
| '/login'
+ | '/setup'
| '/dashboard/domains'
| '/dashboard/notes'
| '/dashboard/servers'
| '/dashboard/services'
| '/dashboard/users'
+ | '/invite/$token'
| '/dashboard/'
| '/dashboard/domains/$domainId'
| '/dashboard/domains/new'
@@ -196,12 +226,15 @@ export interface FileRouteTypes {
fileRoutesByTo: FileRoutesByTo
to:
| '/'
+ | '/change-password'
| '/login'
+ | '/setup'
| '/dashboard/domains'
| '/dashboard/notes'
| '/dashboard/servers'
| '/dashboard/services'
| '/dashboard/users'
+ | '/invite/$token'
| '/dashboard'
| '/dashboard/domains/$domainId'
| '/dashboard/domains/new'
@@ -214,13 +247,16 @@ export interface FileRouteTypes {
id:
| '__root__'
| '/'
+ | '/change-password'
| '/dashboard'
| '/login'
+ | '/setup'
| '/dashboard/domains'
| '/dashboard/notes'
| '/dashboard/servers'
| '/dashboard/services'
| '/dashboard/users'
+ | '/invite/$token'
| '/dashboard/'
| '/dashboard/domains_/$domainId'
| '/dashboard/domains_/new'
@@ -234,12 +270,22 @@ export interface FileRouteTypes {
}
export interface RootRouteChildren {
IndexRoute: typeof IndexRoute
+ ChangePasswordRoute: typeof ChangePasswordRoute
DashboardRoute: typeof DashboardRouteWithChildren
LoginRoute: typeof LoginRoute
+ SetupRoute: typeof SetupRoute
+ InviteTokenRoute: typeof InviteTokenRoute
}
declare module '@tanstack/react-router' {
interface FileRoutesByPath {
+ '/setup': {
+ id: '/setup'
+ path: '/setup'
+ fullPath: '/setup'
+ preLoaderRoute: typeof SetupRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/login': {
id: '/login'
path: '/login'
@@ -254,6 +300,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof DashboardRouteImport
parentRoute: typeof rootRouteImport
}
+ '/change-password': {
+ id: '/change-password'
+ path: '/change-password'
+ fullPath: '/change-password'
+ preLoaderRoute: typeof ChangePasswordRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/': {
id: '/'
path: '/'
@@ -268,6 +321,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof DashboardIndexRouteImport
parentRoute: typeof DashboardRoute
}
+ '/invite/$token': {
+ id: '/invite/$token'
+ path: '/invite/$token'
+ fullPath: '/invite/$token'
+ preLoaderRoute: typeof InviteTokenRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/dashboard/users': {
id: '/dashboard/users'
path: '/users'
@@ -402,8 +462,11 @@ const DashboardRouteWithChildren = DashboardRoute._addFileChildren(
const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute,
+ ChangePasswordRoute: ChangePasswordRoute,
DashboardRoute: DashboardRouteWithChildren,
LoginRoute: LoginRoute,
+ SetupRoute: SetupRoute,
+ InviteTokenRoute: InviteTokenRoute,
}
export const routeTree = rootRouteImport
._addFileChildren(rootRouteChildren)
diff --git a/apps/web/src/routes/change-password.tsx b/apps/web/src/routes/change-password.tsx
new file mode 100644
index 0000000..5736da9
--- /dev/null
+++ b/apps/web/src/routes/change-password.tsx
@@ -0,0 +1,236 @@
+import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
+} from "@minmon/ui/components/alert";
+import { Button } from "@minmon/ui/components/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+} from "@minmon/ui/components/card";
+import {
+ Field,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+} from "@minmon/ui/components/field";
+import { Input } from "@minmon/ui/components/input";
+import { useForm } from "@tanstack/react-form";
+import { createFileRoute, useNavigate } from "@tanstack/react-router";
+import { KeyRound, Loader2, ShieldCheck } from "lucide-react";
+import { toast } from "sonner";
+import z from "zod";
+
+import { requireInitialPasswordChange } from "@/lib/protected-route";
+import { formatErrorMessage } from "@/utils/errors";
+import { queryClient, trpcClient } from "@/utils/trpc";
+
+const passwordSchema = z
+ .object({
+ currentPassword: z.string().min(1, "Enter your initial password"),
+ newPassword: z.string().min(8, "Password must be at least 8 characters"),
+ confirmPassword: z.string(),
+ })
+ .refine((value) => value.newPassword === value.confirmPassword, {
+ message: "Passwords do not match",
+ path: ["confirmPassword"],
+ });
+
+export const Route = createFileRoute("/change-password")({
+ beforeLoad: requireInitialPasswordChange,
+ component: ChangePasswordPage,
+});
+
+type FormError = string | { message?: string } | null | undefined;
+
+function fieldErrors(errors: FormError[]) {
+ return errors
+ .map((error) =>
+ typeof error === "string"
+ ? { message: error }
+ : error?.message
+ ? error
+ : null,
+ )
+ .filter((error): error is { message: string } => Boolean(error));
+}
+
+function ChangePasswordPage() {
+ const { session } = Route.useRouteContext();
+ const navigate = useNavigate();
+ const form = useForm({
+ defaultValues: {
+ currentPassword: "",
+ newPassword: "",
+ confirmPassword: "",
+ },
+ validators: {
+ onSubmit: passwordSchema,
+ },
+ onSubmit: async ({ value }) => {
+ try {
+ await trpcClient.users.changeInitialPassword.mutate({
+ currentPassword: value.currentPassword,
+ newPassword: value.newPassword,
+ });
+ await queryClient.invalidateQueries();
+ toast.success("Password updated");
+ await navigate({ to: "/dashboard" });
+ } catch (error) {
+ toast.error(formatErrorMessage(error, "Could not update the password"));
+ }
+ },
+ });
+
+ return (
+
+
+
+
+
+
+
+ Choose your own password
+
+
+ An administrator created {session.data?.user.email} with an initial
+ password. Replace it before entering the monitoring console.
+
+
+
+
+
+
+
+
+ ({
+ canSubmit: state.canSubmit,
+ isSubmitting: state.isSubmitting,
+ })}
+ >
+ {({ canSubmit, isSubmitting }) => (
+
+ {isSubmitting ? (
+
+ ) : (
+
+ )}
+ {isSubmitting ? "Updating password…" : "Update password"}
+
+ )}
+
+
+
+
+ );
+}
diff --git a/apps/web/src/routes/dashboard.users.tsx b/apps/web/src/routes/dashboard.users.tsx
index 0fd368f..8041552 100644
--- a/apps/web/src/routes/dashboard.users.tsx
+++ b/apps/web/src/routes/dashboard.users.tsx
@@ -1,14 +1,58 @@
+import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
+} from "@minmon/ui/components/alert";
import { Button } from "@minmon/ui/components/button";
-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@minmon/ui/components/card";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@minmon/ui/components/card";
import { Checkbox } from "@minmon/ui/components/checkbox";
+import {
+ Field,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+ FieldLegend,
+ FieldSet,
+} from "@minmon/ui/components/field";
+import { Input } from "@minmon/ui/components/input";
import { StatusBadge } from "@minmon/ui/components/status-badge";
+import {
+ ToggleGroup,
+ ToggleGroupItem,
+} from "@minmon/ui/components/toggle-group";
import { useForm } from "@tanstack/react-form";
import { useMutation, useQuery } from "@tanstack/react-query";
import { createFileRoute } from "@tanstack/react-router";
+import {
+ Check,
+ Copy,
+ KeyRound,
+ Link2,
+ Loader2,
+ RefreshCw,
+ ShieldCheck,
+ UserPlus,
+ X,
+} from "lucide-react";
+import { useEffect, useState } from "react";
import { toast } from "sonner";
import z from "zod";
-import { ConfirmDeleteIconButton, FormCard, PageSection, QueryStateCard, ResourceListCard, TextField } from "@/components/dashboard-ui";
+import {
+ ConfirmDeleteIconButton,
+ FormCard,
+ PageSection,
+ QueryStateCard,
+ ResourceListCard,
+} from "@/components/dashboard-ui";
+import { formatErrorMessage } from "@/utils/errors";
import { queryClient, trpc, trpcClient } from "@/utils/trpc";
export const Route = createFileRoute("/dashboard/users")({
@@ -28,13 +72,97 @@ type UserCreateFormValues = {
roleIds: string[];
};
+type FormError = string | { message?: string } | null | undefined;
+
const userCreateSchema = z.object({
- name: z.string().min(2, "Name must be at least 2 characters"),
- email: z.email("Invalid email address"),
+ name: z.string().trim().min(2, "Name must be at least 2 characters"),
+ email: z.email("Enter a valid email address"),
password: z.string().min(8, "Password must be at least 8 characters"),
roleIds: z.array(z.string()).min(1, "Select at least one role"),
});
+const invitationCreateSchema = z.object({
+ roleIds: z.array(z.string()).min(1, "Select at least one role"),
+});
+
+function fieldErrors(errors: FormError[]) {
+ return errors
+ .map((error) =>
+ typeof error === "string"
+ ? { message: error }
+ : error?.message
+ ? error
+ : null,
+ )
+ .filter((error): error is { message: string } => Boolean(error));
+}
+
+function RevokeInvitationButton({
+ disabled,
+ onConfirm,
+}: {
+ disabled: boolean;
+ onConfirm: () => void;
+}) {
+ const [isConfirming, setIsConfirming] = useState(false);
+
+ useEffect(() => {
+ if (!isConfirming) return;
+
+ const timeoutId = window.setTimeout(() => setIsConfirming(false), 4000);
+ return () => window.clearTimeout(timeoutId);
+ }, [isConfirming]);
+
+ useEffect(() => {
+ if (disabled) setIsConfirming(false);
+ }, [disabled]);
+
+ return (
+
setIsConfirming(false)}
+ onClick={() => {
+ if (isConfirming) {
+ onConfirm();
+ setIsConfirming(false);
+ return;
+ }
+
+ setIsConfirming(true);
+ }}
+ >
+ {isConfirming ? (
+
+ ) : (
+
+ )}
+ {isConfirming ? "Confirm revoke" : "Revoke"}
+
+ );
+}
+
+function defaultRoleIds(roles: RoleOption[]) {
+ return [
+ roles.find((role) => role.name === "Viewer")?.id ?? roles[0]?.id ?? "",
+ ].filter(Boolean);
+}
+
+function inviteUrl(token: string) {
+ return `${window.location.origin}/invite/${encodeURIComponent(token)}`;
+}
+
+async function copyInvitationLink(token: string) {
+ try {
+ await navigator.clipboard.writeText(inviteUrl(token));
+ toast.success("Invitation link copied");
+ } catch {
+ toast.error("Could not copy the invitation link");
+ }
+}
+
function RoleBadges({ roles }: { roles: { id: string; name: string }[] }) {
if (!roles.length) {
return
No roles ;
@@ -43,7 +171,16 @@ function RoleBadges({ roles }: { roles: { id: string; name: string }[] }) {
return (
{roles.map((role) => (
-
+
{role.name}
))}
@@ -51,17 +188,545 @@ function RoleBadges({ roles }: { roles: { id: string; name: string }[] }) {
);
}
-function RoleAssignmentCard({ roles, permissions }: { roles: RoleOption[]; permissions: string[] }) {
+function RoleSelector({
+ roles,
+ value,
+ onChange,
+ errors,
+ idPrefix,
+}: {
+ roles: RoleOption[];
+ value: string[];
+ onChange: (value: string[]) => void;
+ errors: FormError[];
+ idPrefix: string;
+}) {
+ const normalizedErrors = fieldErrors(errors);
+
+ return (
+
+ Initial roles
+
+ Roles control which areas and actions are available after sign-in.
+
+
+ {roles.map((role) => {
+ const checked = value.includes(role.id);
+ const nextRoleIds = checked
+ ? value.filter((roleId) => roleId !== role.id)
+ : [...value, role.id];
+ const id = `${idPrefix}-${role.id}`;
+
+ return (
+
+ onChange(nextRoleIds)}
+ />
+
+
+ {role.name}
+
+ {role.description}
+
+
+
+
+ );
+ })}
+
+
+
+ );
+}
+
+function CreationMethodSelector({
+ value,
+ onChange,
+}: {
+ value: "password" | "invite";
+ onChange: (value: "password" | "invite") => void;
+}) {
+ return (
+
+ Account setup method
+ {
+ const method = nextValue[0];
+ if (method === "password" || method === "invite") onChange(method);
+ }}
+ >
+
+
+ Initial password
+
+
+
+ Invitation link
+
+
+
+ Set a temporary credential now, or let the recipient choose every
+ identity field through a one-time link.
+
+
+ );
+}
+
+function DirectUserForm({
+ roles,
+ onMethodChange,
+}: {
+ roles: RoleOption[];
+ onMethodChange: (value: "password" | "invite") => void;
+}) {
+ const createUser = useMutation({
+ mutationFn: async (values: UserCreateFormValues) =>
+ trpcClient.users.create.mutate(values),
+ onSuccess: async () => {
+ toast.success("User created with an initial password");
+ form.reset();
+ await queryClient.invalidateQueries();
+ },
+ onError: (error) =>
+ toast.error(formatErrorMessage(error, "Could not create the user")),
+ });
+ const form = useForm({
+ defaultValues: {
+ name: "",
+ email: "",
+ password: "",
+ roleIds: defaultRoleIds(roles),
+ } satisfies UserCreateFormValues,
+ validators: {
+ onSubmit: userCreateSchema,
+ },
+ onSubmit: async ({ value }) => {
+ await createUser.mutateAsync(value);
+ },
+ });
+
+ return (
+
+ );
+}
+
+function InvitationForm({
+ roles,
+ onMethodChange,
+}: {
+ roles: RoleOption[];
+ onMethodChange: (value: "password" | "invite") => void;
+}) {
+ const [latestToken, setLatestToken] = useState(null);
+ const createInvitation = useMutation({
+ mutationFn: async (values: { roleIds: string[] }) =>
+ trpcClient.users.invitations.create.mutate(values),
+ onSuccess: async (invitation) => {
+ form.reset();
+ setLatestToken(invitation?.token ?? null);
+ if (invitation?.token) await copyInvitationLink(invitation.token);
+ await queryClient.invalidateQueries();
+ },
+ onError: (error) =>
+ toast.error(formatErrorMessage(error, "Could not create the invitation")),
+ });
+ const form = useForm({
+ defaultValues: {
+ roleIds: defaultRoleIds(roles),
+ },
+ validators: {
+ onSubmit: invitationCreateSchema,
+ },
+ onSubmit: async ({ value }) => {
+ await createInvitation.mutateAsync(value);
+ },
+ });
+
+ return (
+
+ );
+}
+
+function CreateAccessCard({ roles }: { roles: RoleOption[] }) {
+ const [method, setMethod] = useState<"password" | "invite">("password");
+ return method === "password" ? (
+
+ ) : (
+
+ );
+}
+
+function InvitationListCard() {
+ const invitations = useQuery(trpc.users.invitations.list.queryOptions());
+ const revokeInvitation = useMutation({
+ mutationFn: async (id: string) =>
+ trpcClient.users.invitations.revoke.mutate({ id }),
+ onSuccess: async () => {
+ toast.success("Invitation revoked");
+ await queryClient.invalidateQueries();
+ },
+ onError: (error) =>
+ toast.error(formatErrorMessage(error, "Could not revoke the invitation")),
+ });
+ const replaceInvitation = useMutation({
+ mutationFn: async (id: string) =>
+ trpcClient.users.invitations.reissue.mutate({ id }),
+ onSuccess: async (replacement) => {
+ if (replacement?.token) await copyInvitationLink(replacement.token);
+ await queryClient.invalidateQueries();
+ },
+ onError: (error) =>
+ toast.error(
+ formatErrorMessage(error, "Could not replace the invitation"),
+ ),
+ });
+
+ if (invitations.isLoading) {
+ return (
+
+ );
+ }
+
+ if (invitations.isError || !invitations.data) {
+ return (
+
+ );
+ }
+
+ return (
+ (
+
+ {new Date(item.createdAt).toLocaleString()}
+
+ ),
+ },
+ {
+ key: "roles",
+ header: "Roles",
+ render: (item: (typeof invitations.data)[number]) => (
+
+ ),
+ },
+ {
+ key: "status",
+ header: "Status",
+ render: (item: (typeof invitations.data)[number]) => (
+
+ {item.status}
+
+ ),
+ },
+ {
+ key: "actions",
+ header: "Actions",
+ render: (item: (typeof invitations.data)[number]) =>
+ item.status === "pending" ? (
+
+ item.token && copyInvitationLink(item.token)}
+ >
+
+ Copy
+
+ replaceInvitation.mutate(item.id)}
+ >
+
+ Replace link
+
+ revokeInvitation.mutate(item.id)}
+ />
+
+ ) : (
+
+ No actions available
+
+ ),
+ },
+ ]}
+ items={invitations.data}
+ emptyTitle="No invitation links"
+ emptyDescription="Create an invitation when someone should choose their own account details."
+ controls={{
+ search: {
+ placeholder: "Search role or status…",
+ getText: (item) =>
+ [item.status, ...item.roles.map((role) => role.name)].join(" "),
+ },
+ filter: {
+ label: "Filter by status",
+ allLabel: "All statuses",
+ options: [
+ { value: "pending", label: "Pending" },
+ { value: "accepted", label: "Accepted" },
+ { value: "revoked", label: "Revoked" },
+ ],
+ getValue: (item) => item.status,
+ },
+ }}
+ />
+ );
+}
+
+function RoleAssignmentCard({
+ roles,
+ permissions,
+ currentUserId,
+}: {
+ roles: RoleOption[];
+ permissions: string[];
+ currentUserId: string;
+}) {
const users = useQuery(trpc.users.list.queryOptions());
const allowedPermissions = new Set(permissions);
const updateRoles = useMutation({
- mutationFn: async ({ userId, roleIds }: { userId: string; roleIds: string[] }) =>
- trpcClient.users.updateRoles.mutate({ userId, roleIds }),
+ mutationFn: async ({
+ userId,
+ roleIds,
+ }: {
+ userId: string;
+ roleIds: string[];
+ }) => trpcClient.users.updateRoles.mutate({ userId, roleIds }),
onSuccess: async () => {
toast.success("User roles updated");
await queryClient.invalidateQueries();
},
- onError: (error) => toast.error(error.message),
+ onError: (error) =>
+ toast.error(formatErrorMessage(error, "Could not update roles")),
});
const removeUser = useMutation({
mutationFn: async (id: string) => trpcClient.users.delete.mutate({ id }),
@@ -69,17 +734,32 @@ function RoleAssignmentCard({ roles, permissions }: { roles: RoleOption[]; permi
toast.success("User deleted");
await queryClient.invalidateQueries();
},
- onError: (error) => toast.error(error.message),
+ onError: (error) =>
+ toast.error(formatErrorMessage(error, "Could not delete the user")),
});
if (users.isLoading) {
- return ;
+ return (
+
+ );
}
if (users.isError || !users.data) {
- return ;
+ return (
+
+ );
}
+ const adminCount = users.data.filter((item) =>
+ item.roles.some((assignedRole) => assignedRole.id === "role_admin"),
+ ).length;
+
return (
(
-
{item.name}
-
{item.email}
+
+ {item.name}
+ {item.mustChangePassword ? (
+ Initial password
+ ) : null}
+
+
+ {item.email}
+
),
},
{
key: "roles",
header: "Current roles",
- render: (item: (typeof users.data)[number]) => ,
+ render: (item: (typeof users.data)[number]) => (
+
+ ),
},
...(allowedPermissions.has("users.assignRoles")
? [
@@ -110,22 +799,45 @@ function RoleAssignmentCard({ roles, permissions }: { roles: RoleOption[]; permi
key: "assign",
header: "Assign roles",
render: (item: (typeof users.data)[number]) => {
- const assignedRoleIds = new Set(item.roles.map((role) => role.id));
+ const assignedRoleIds = new Set(
+ item.roles.map((assignedRole) => assignedRole.id),
+ );
+ const isLastAdmin =
+ assignedRoleIds.has("role_admin") && adminCount === 1;
return (
{roles.map((role) => {
const checked = assignedRoleIds.has(role.id);
const nextRoleIds = checked
- ? item.roles.map((assignedRole) => assignedRole.id).filter((roleId) => roleId !== role.id)
- : [...item.roles.map((assignedRole) => assignedRole.id), role.id];
+ ? item.roles
+ .map((assignedRole) => assignedRole.id)
+ .filter((roleId) => roleId !== role.id)
+ : [
+ ...item.roles.map(
+ (assignedRole) => assignedRole.id,
+ ),
+ role.id,
+ ];
+ const disabled =
+ updateRoles.isPending ||
+ nextRoleIds.length === 0 ||
+ (role.id === "role_admin" && isLastAdmin);
return (
-
+
updateRoles.mutate({ userId: item.id, roleIds: nextRoleIds })}
+ disabled={disabled}
+ onCheckedChange={() =>
+ updateRoles.mutate({
+ userId: item.id,
+ roleIds: nextRoleIds,
+ })
+ }
/>
{role.name}
@@ -143,24 +855,39 @@ function RoleAssignmentCard({ roles, permissions }: { roles: RoleOption[]; permi
key: "actions",
header: "Actions",
className: "w-20",
- render: (item: (typeof users.data)[number]) => (
- removeUser.mutate(item.id)}
- />
- ),
+ render: (item: (typeof users.data)[number]) => {
+ const isLastAdmin =
+ item.roles.some(
+ (assignedRole) => assignedRole.id === "role_admin",
+ ) && adminCount === 1;
+ return (
+ removeUser.mutate(item.id)}
+ />
+ );
+ },
},
]
: []),
]}
items={users.data}
emptyTitle="No users found"
- emptyDescription="Users appear here after they sign up or are seeded."
+ emptyDescription="Users appear here after an administrator creates an account or an invitation is accepted."
controls={{
search: {
placeholder: "Search name, email, or role…",
- getText: (item) => [item.name, item.email, ...item.roles.map((role) => role.name)].join(" "),
+ getText: (item) =>
+ [
+ item.name,
+ item.email,
+ ...item.roles.map((role) => role.name),
+ ].join(" "),
},
filter: {
label: "Filter by role",
@@ -173,168 +900,73 @@ function RoleAssignmentCard({ roles, permissions }: { roles: RoleOption[]; permi
);
}
-function CreateUserCard({ roles }: { roles: RoleOption[] }) {
- const createUser = useMutation({
- mutationFn: async (values: UserCreateFormValues) => trpcClient.users.create.mutate(values),
- onSuccess: async () => {
- toast.success("User created");
- form.reset();
- await queryClient.invalidateQueries();
- },
- onError: (error) => toast.error(error.message),
- });
-
- const form = useForm({
- defaultValues: {
- name: "",
- email: "",
- password: "",
- roleIds: [roles.find((role) => role.name === "Viewer")?.id ?? roles[0]?.id ?? ""].filter(Boolean),
- } satisfies UserCreateFormValues,
- onSubmit: async ({ value }) => {
- await createUser.mutateAsync(value);
- },
- validators: {
- onSubmit: userCreateSchema,
- },
- });
-
- return (
-
- );
-}
-
function RouteComponent() {
const roles = useQuery(trpc.users.roles.queryOptions());
const me = useQuery(trpc.users.me.queryOptions());
if (roles.isLoading || me.isLoading) {
- return ;
+ return (
+
+ );
}
if (roles.isError || !roles.data || me.isError || !me.data) {
- return ;
+ return (
+
+ );
}
const allowedPermissions = new Set(me.data.permissions);
return (
-
+
- {allowedPermissions.has("users.create") ?
: null}
+ {allowedPermissions.has("users.create") ? (
+
+ ) : null}
+ {allowedPermissions.has("users.create") ?
: null}
Role guide
- Default RBAC roles seeded by the application.
+
+ Default RBAC roles seeded by the application.
+
{roles.data.map((role) => (
-
+
{role.name}
- {role.description}
+
+ {role.description}
+
))}
-
+
);
diff --git a/apps/web/src/routes/index.tsx b/apps/web/src/routes/index.tsx
index 1ef3955..bfdbd06 100644
--- a/apps/web/src/routes/index.tsx
+++ b/apps/web/src/routes/index.tsx
@@ -1,13 +1,27 @@
import { createFileRoute, redirect } from "@tanstack/react-router";
import { authClient } from "@/lib/auth-client";
+import { trpcClient } from "@/utils/trpc";
export const Route = createFileRoute("/")({
beforeLoad: async () => {
- const session = await authClient.getSession();
+ const [session, onboarding] = await Promise.all([
+ authClient.getSession(),
+ trpcClient.onboarding.status.query(),
+ ]);
+
+ if (onboarding.needsSetup) {
+ throw redirect({
+ to: "/setup",
+ });
+ }
throw redirect({
- to: session.data ? "/dashboard" : "/login",
+ to: session.data?.user.mustChangePassword
+ ? "/change-password"
+ : session.data
+ ? "/dashboard"
+ : "/login",
});
},
component: () => null,
diff --git a/apps/web/src/routes/invite.$token.tsx b/apps/web/src/routes/invite.$token.tsx
new file mode 100644
index 0000000..7d85821
--- /dev/null
+++ b/apps/web/src/routes/invite.$token.tsx
@@ -0,0 +1,410 @@
+import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
+} from "@minmon/ui/components/alert";
+import { Button } from "@minmon/ui/components/button";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+} from "@minmon/ui/components/card";
+import {
+ Field,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+} from "@minmon/ui/components/field";
+import { Input } from "@minmon/ui/components/input";
+import { Separator } from "@minmon/ui/components/separator";
+import { StatusBadge } from "@minmon/ui/components/status-badge";
+import { useForm } from "@tanstack/react-form";
+import { useQuery } from "@tanstack/react-query";
+import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
+import {
+ CircleOff,
+ KeyRound,
+ Loader2,
+ LogIn,
+ ShieldCheck,
+ TicketCheck,
+ UserRoundPlus,
+} from "lucide-react";
+import { toast } from "sonner";
+import z from "zod";
+
+import Loader from "@/components/loader";
+import { authClient } from "@/lib/auth-client";
+import { formatErrorMessage } from "@/utils/errors";
+import { queryClient, trpc, trpcClient } from "@/utils/trpc";
+
+const acceptInvitationSchema = z
+ .object({
+ name: z.string().trim().min(2, "Name must be at least 2 characters"),
+ email: z.email("Enter a valid email address"),
+ password: z.string().min(8, "Password must be at least 8 characters"),
+ confirmPassword: z.string(),
+ })
+ .refine((value) => value.password === value.confirmPassword, {
+ message: "Passwords do not match",
+ path: ["confirmPassword"],
+ });
+
+export const Route = createFileRoute("/invite/$token")({
+ component: InvitePage,
+});
+
+type FormError = string | { message?: string } | null | undefined;
+
+function fieldErrors(errors: FormError[]) {
+ return errors
+ .map((error) =>
+ typeof error === "string"
+ ? { message: error }
+ : error?.message
+ ? error
+ : null,
+ )
+ .filter((error): error is { message: string } => Boolean(error));
+}
+
+function InviteUnavailable({
+ status,
+}: {
+ status: "invalid" | "revoked" | "accepted";
+}) {
+ const session = authClient.useSession();
+ const content = {
+ invalid: {
+ title: "Invitation not found",
+ description:
+ "Check that the complete link was copied into the address bar.",
+ },
+ revoked: {
+ title: "Invitation revoked",
+ description:
+ "An administrator closed this link. Ask them to create a new invitation.",
+ },
+ accepted: {
+ title: "Invitation already used",
+ description:
+ "This one-time link has already created an account and cannot be used again.",
+ },
+ }[status];
+
+ return (
+
+
+
+
+
+
+ {content.title}
+ {content.description}
+
+
+ }
+ nativeButton={false}
+ >
+
+ {session.data ? "Return to dashboard" : "Go to sign in"}
+
+
+
+
+ );
+}
+
+function InvitePage() {
+ const { token } = Route.useParams();
+ const navigate = useNavigate();
+ const session = authClient.useSession();
+ const invitation = useQuery(
+ trpc.users.invitations.inspect.queryOptions({ token }),
+ );
+ const form = useForm({
+ defaultValues: {
+ name: "",
+ email: "",
+ password: "",
+ confirmPassword: "",
+ },
+ validators: {
+ onSubmit: acceptInvitationSchema,
+ },
+ onSubmit: async ({ value }) => {
+ try {
+ await trpcClient.users.invitations.accept.mutate({
+ token,
+ name: value.name,
+ email: value.email,
+ password: value.password,
+ });
+
+ if (session.data) {
+ await authClient.signOut();
+ }
+
+ const signIn = await authClient.signIn.email({
+ email: value.email,
+ password: value.password,
+ });
+
+ if (signIn.error) {
+ toast.error("Account created. Sign in with your new password.");
+ await navigate({ to: "/login" });
+ return;
+ }
+
+ await queryClient.invalidateQueries();
+ toast.success("Account created from invitation");
+ await navigate({ to: "/dashboard" });
+ } catch (error) {
+ toast.error(
+ formatErrorMessage(error, "Could not accept the invitation"),
+ );
+ await invitation.refetch();
+ }
+ },
+ });
+
+ if (invitation.isLoading) {
+ return ;
+ }
+
+ if (invitation.isError || !invitation.data) {
+ return ;
+ }
+
+ if (invitation.data.status !== "pending") {
+ return ;
+ }
+
+ return (
+
+
+
+
+
+
+
+
+ One-time invitation
+
+
+ Join this Minmon console.
+
+
+ Choose the identity and password you will use. This link closes as
+ soon as your account is created.
+
+
+
+
+
+
+
Access granted by this link
+
+ {invitation.data.roles.map((role) => (
+
+ {role.name}
+
+ ))}
+
+
+ An administrator can change these roles later from User
+ management.
+
+
+
+
+
+
+
+ Create your account
+
+
+ Your email is stored as unverified until email verification is
+ added.
+
+
+
+ {session.data ? (
+
+
+
+ Currently signed in as {session.data.user.email}
+
+
+ Finish this form to switch this browser to the newly created
+ account.
+
+
+ ) : null}
+
+
({
+ canSubmit: state.canSubmit,
+ isSubmitting: state.isSubmitting,
+ })}
+ >
+ {({ canSubmit, isSubmitting }) => (
+
+ {isSubmitting ? (
+
+ ) : (
+
+ )}
+ {isSubmitting ? "Creating account…" : "Create account"}
+
+ )}
+
+
+
+
+ Creating the account consumes this invitation. It has no expiration
+ date, but an administrator may revoke it before use.
+
+
+
+
+ );
+}
diff --git a/apps/web/src/routes/login.tsx b/apps/web/src/routes/login.tsx
index d83628e..8954863 100644
--- a/apps/web/src/routes/login.tsx
+++ b/apps/web/src/routes/login.tsx
@@ -1,7 +1,27 @@
import SignInForm from "@/components/sign-in-form";
-import { createFileRoute } from "@tanstack/react-router";
+import { authClient } from "@/lib/auth-client";
+import { trpcClient } from "@/utils/trpc";
+import { createFileRoute, redirect } from "@tanstack/react-router";
export const Route = createFileRoute("/login")({
+ beforeLoad: async () => {
+ const [session, onboarding] = await Promise.all([
+ authClient.getSession(),
+ trpcClient.onboarding.status.query(),
+ ]);
+
+ if (onboarding.needsSetup) {
+ throw redirect({ to: "/setup" });
+ }
+
+ if (session.data) {
+ throw redirect({
+ to: session.data.user.mustChangePassword
+ ? "/change-password"
+ : "/dashboard",
+ });
+ }
+ },
component: RouteComponent,
});
diff --git a/apps/web/src/routes/setup.tsx b/apps/web/src/routes/setup.tsx
new file mode 100644
index 0000000..0fe4d55
--- /dev/null
+++ b/apps/web/src/routes/setup.tsx
@@ -0,0 +1,346 @@
+import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
+} from "@minmon/ui/components/alert";
+import { Button } from "@minmon/ui/components/button";
+import {
+ Field,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLabel,
+} from "@minmon/ui/components/field";
+import { Input } from "@minmon/ui/components/input";
+import { Separator } from "@minmon/ui/components/separator";
+import { useForm } from "@tanstack/react-form";
+import { createFileRoute, redirect, useNavigate } from "@tanstack/react-router";
+import {
+ Check,
+ Loader2,
+ LockKeyhole,
+ ShieldCheck,
+ UserRound,
+} from "lucide-react";
+import { toast } from "sonner";
+import z from "zod";
+
+import { authClient } from "@/lib/auth-client";
+import { formatErrorMessage } from "@/utils/errors";
+import { queryClient, trpcClient } from "@/utils/trpc";
+
+const setupSchema = z
+ .object({
+ name: z.string().trim().min(2, "Name must be at least 2 characters"),
+ email: z.email("Enter a valid email address"),
+ password: z.string().min(8, "Password must be at least 8 characters"),
+ confirmPassword: z.string(),
+ })
+ .refine((value) => value.password === value.confirmPassword, {
+ message: "Passwords do not match",
+ path: ["confirmPassword"],
+ });
+
+export const Route = createFileRoute("/setup")({
+ beforeLoad: async () => {
+ const onboarding = await trpcClient.onboarding.status.query();
+ if (!onboarding.needsSetup) {
+ throw redirect({ to: "/" });
+ }
+ },
+ component: SetupPage,
+});
+
+type FormError = string | { message?: string } | null | undefined;
+
+function fieldErrors(errors: FormError[]) {
+ return errors
+ .map((error) =>
+ typeof error === "string"
+ ? { message: error }
+ : error?.message
+ ? error
+ : null,
+ )
+ .filter((error): error is { message: string } => Boolean(error));
+}
+
+const readinessSteps = [
+ {
+ icon: UserRound,
+ title: "Create the owner",
+ description: "The first account receives administrator access.",
+ },
+ {
+ icon: LockKeyhole,
+ title: "Close registration",
+ description: "Public sign-up stays disabled after this account is created.",
+ },
+ {
+ icon: ShieldCheck,
+ title: "Open the console",
+ description: "You will be signed in and taken straight to the dashboard.",
+ },
+] as const;
+
+function SetupPage() {
+ const navigate = useNavigate();
+ const form = useForm({
+ defaultValues: {
+ name: "",
+ email: "",
+ password: "",
+ confirmPassword: "",
+ },
+ validators: {
+ onSubmit: setupSchema,
+ },
+ onSubmit: async ({ value }) => {
+ try {
+ await trpcClient.onboarding.createAdmin.mutate({
+ name: value.name,
+ email: value.email,
+ password: value.password,
+ });
+
+ const signIn = await authClient.signIn.email({
+ email: value.email,
+ password: value.password,
+ });
+
+ if (signIn.error) {
+ throw signIn.error;
+ }
+
+ await queryClient.invalidateQueries();
+ toast.success("Minmon is ready");
+ await navigate({ to: "/dashboard" });
+ } catch (error) {
+ toast.error(formatErrorMessage(error, "Could not complete setup"));
+ }
+ },
+ });
+
+ return (
+
+
+
+
+
+ First-run initialization
+
+
+
+ Put one trusted operator in control.
+
+
+ Minmon found an empty user directory. Create the owner account
+ that will manage this private monitoring console.
+
+
+
+
+
+ {readinessSteps.map(({ icon: Icon, title, description }, index) => (
+
+
+
+
+
+ {index < readinessSteps.length - 1 ? (
+
+ ) : null}
+
+
+
+
+ 0{index + 1}
+
+
{title}
+
+
+ {description}
+
+
+
+ ))}
+
+
+
+
+
+
+
+ Database connection ready
+
+
+ Create administrator
+
+
+ This is the only account that can be created without an
+ invitation.
+
+
+
+
+
+
({
+ canSubmit: state.canSubmit,
+ isSubmitting: state.isSubmitting,
+ })}
+ >
+ {({ canSubmit, isSubmitting }) => (
+
+ {isSubmitting ? (
+
+ ) : (
+
+ )}
+ {isSubmitting
+ ? "Creating administrator…"
+ : "Create administrator"}
+
+ )}
+
+
+
+
+
+ );
+}
diff --git a/docs/run-instructions.md b/docs/run-instructions.md
index ddbd54a..85954bd 100644
--- a/docs/run-instructions.md
+++ b/docs/run-instructions.md
@@ -6,8 +6,14 @@ Minmon is a student-friendly web dashboard for managing private servers, service
## Current Main Features
-- Admin sign-in with better-auth
+- First-run administrator registration when no users exist
+- Better Auth sign-in with ordinary public registration disabled
+- User creation by initial password or one-time invitation link
+- Invitation copy, revoke, replace, accepted, and revoked lifecycle states
+- Forced password replacement for administrator-created initial passwords
- Root route (`/`) redirects automatically:
+ - no users -> `/setup`
+ - initial-password replacement required -> `/change-password`
- logged in -> `/dashboard`
- not logged in -> `/login`
- Dashboard summary for:
@@ -29,12 +35,15 @@ Minmon is a student-friendly web dashboard for managing private servers, service
- service -> server
- domain -> service
- note -> server
-- Sample seeded admin and demo dataset
+- Optional sample admin and demo dataset
## Current Route Structure
- `/` -> auth-based redirect
+- `/setup` -> first administrator registration, available only while there are no users
- `/login` -> sign-in page
+- `/change-password` -> required initial-password replacement
+- `/invite/$token` -> one-time invitation acceptance
- `/dashboard` -> summary page
- `/dashboard/servers` -> server list
- `/dashboard/servers/new` -> create server
@@ -48,6 +57,7 @@ Minmon is a student-friendly web dashboard for managing private servers, service
- `/dashboard/notes` -> note list
- `/dashboard/notes/new` -> create note
- `/dashboard/notes/$noteId` -> note detail + edit
+- `/dashboard/users` -> users, roles, and invitation lifecycle management
## Local Setup
@@ -92,7 +102,25 @@ bun run db:start
bun run db:push
```
-7. Seed sample data
+7. Run the apps
+
+```bash
+bun run dev
+```
+
+8. Open the app
+
+- Web: `http://localhost:5173`
+- API: `http://localhost:3000`
+
+With an empty user table, the root and login routes redirect to `/setup`. Create the
+first administrator there. The backend serializes first-account creation and rejects
+any later public registration attempt.
+
+### Optional demo seed
+
+The explicit demo seed is still available when the sample inventory and fixed demo
+administrator are needed:
```bash
bun run --filter @minmon/db db:seed
@@ -103,17 +131,6 @@ Seeded admin login:
- Email: `admin@minmon.local`
- Password: `admin12345`
-8. Run the apps
-
-```bash
-bun run dev
-```
-
-9. Open the app
-
-- Web: `http://localhost:5173`
-- API: `http://localhost:3000`
-
## Docker Compose Deployment
Run the deployable stack with one command:
@@ -128,11 +145,12 @@ Default Docker endpoints:
- Web: `http://localhost:3001`
- API: `http://localhost:3000`
-The Compose stack starts PostgreSQL, applies the schema, and seeds the sample admin only if the users table is empty.
+The Compose stack starts PostgreSQL, applies the schema, and ensures the default
+roles and permissions exist. It does not seed a default user; finish initialization
+from the first-run setup screen.
Docker Compose reads the root `.env` file automatically. Edit it before startup if you need different ports, public URLs, credentials, or secrets.
-
## Current Behavior Notes
### List Ordering
diff --git a/packages/api/src/context.ts b/packages/api/src/context.ts
index 5026dd5..0ad0f89 100644
--- a/packages/api/src/context.ts
+++ b/packages/api/src/context.ts
@@ -21,7 +21,11 @@ async function getAuthorization(userId: string) {
.where(eq(userRole.userId, userId));
return {
- roles: Array.from(new Map(rows.map((row) => [row.roleId, { id: row.roleId, name: row.roleName }])).values()),
+ roles: Array.from(
+ new Map(
+ rows.map((row) => [row.roleId, { id: row.roleId, name: row.roleName }]),
+ ).values(),
+ ),
permissions: Array.from(new Set(rows.map((row) => row.permissionName))),
};
}
@@ -31,12 +35,15 @@ export async function createContext({ context }: CreateContextOptions) {
headers: context.request.headers,
});
- const authorization = session ? await getAuthorization(session.user.id) : { roles: [], permissions: [] };
+ const authorization = session
+ ? await getAuthorization(session.user.id)
+ : { roles: [], permissions: [] };
return {
- auth: null,
+ auth,
session,
authorization,
+ requestHeaders: context.request.headers,
};
}
diff --git a/packages/api/src/index.ts b/packages/api/src/index.ts
index da992c4..d7ac8ca 100644
--- a/packages/api/src/index.ts
+++ b/packages/api/src/index.ts
@@ -35,6 +35,13 @@ export function requirePermission(permission: Permission) {
});
}
+ if (ctx.session.user.mustChangePassword) {
+ throw new TRPCError({
+ code: "FORBIDDEN",
+ message: "Change the initial password before using Minmon",
+ });
+ }
+
if (!ctx.authorization.permissions.includes(permission)) {
throw new TRPCError({
code: "FORBIDDEN",
diff --git a/packages/api/src/lib/invitation-token.ts b/packages/api/src/lib/invitation-token.ts
new file mode 100644
index 0000000..e699f5a
--- /dev/null
+++ b/packages/api/src/lib/invitation-token.ts
@@ -0,0 +1,67 @@
+import { env } from "@minmon/env/server";
+
+const textEncoder = new TextEncoder();
+const inviteKeyMaterial = textEncoder.encode(
+ `${env.BETTER_AUTH_SECRET}:minmon-user-invitations:v1`,
+);
+
+const inviteKeyPromise = crypto.subtle
+ .digest("SHA-256", inviteKeyMaterial)
+ .then((digest) =>
+ crypto.subtle.importKey("raw", digest, { name: "AES-GCM" }, false, [
+ "encrypt",
+ "decrypt",
+ ]),
+ );
+
+function encodeBytes(value: ArrayBuffer | Uint8Array) {
+ return Buffer.from(
+ value instanceof Uint8Array ? value : new Uint8Array(value),
+ ).toString("base64url");
+}
+
+function decodeBytes(value: string) {
+ return new Uint8Array(Buffer.from(value, "base64url"));
+}
+
+export async function hashInvitationToken(token: string) {
+ const digest = await crypto.subtle.digest(
+ "SHA-256",
+ textEncoder.encode(token),
+ );
+ return Buffer.from(digest).toString("hex");
+}
+
+export async function createInvitationToken() {
+ const tokenBytes = crypto.getRandomValues(new Uint8Array(32));
+ const token = encodeBytes(tokenBytes);
+ const tokenHash = await hashInvitationToken(token);
+ const tokenIvBytes = crypto.getRandomValues(new Uint8Array(12));
+ const key = await inviteKeyPromise;
+ const encrypted = await crypto.subtle.encrypt(
+ { name: "AES-GCM", iv: tokenIvBytes },
+ key,
+ textEncoder.encode(token),
+ );
+
+ return {
+ token,
+ tokenHash,
+ tokenEncrypted: encodeBytes(encrypted),
+ tokenIv: encodeBytes(tokenIvBytes),
+ };
+}
+
+export async function decryptInvitationToken(
+ tokenEncrypted: string,
+ tokenIv: string,
+) {
+ const key = await inviteKeyPromise;
+ const decrypted = await crypto.subtle.decrypt(
+ { name: "AES-GCM", iv: decodeBytes(tokenIv) },
+ key,
+ decodeBytes(tokenEncrypted),
+ );
+
+ return new TextDecoder().decode(decrypted);
+}
diff --git a/packages/api/src/routers/index.ts b/packages/api/src/routers/index.ts
index 3fd7cfe..daae0da 100644
--- a/packages/api/src/routers/index.ts
+++ b/packages/api/src/routers/index.ts
@@ -3,6 +3,7 @@ import { publicProcedure, router } from "../index";
import { dashboardRouter } from "./dashboard";
import { domainsRouter } from "./domains";
import { notesRouter } from "./notes";
+import { onboardingRouter } from "./onboarding";
import { serversRouter } from "./servers";
import { servicesRouter } from "./services";
import { usersRouter } from "./users";
@@ -11,6 +12,7 @@ export const appRouter = router({
healthCheck: publicProcedure.query(() => {
return "OK";
}),
+ onboarding: onboardingRouter,
dashboard: dashboardRouter,
servers: serversRouter,
services: servicesRouter,
diff --git a/packages/api/src/routers/onboarding.ts b/packages/api/src/routers/onboarding.ts
new file mode 100644
index 0000000..428558e
--- /dev/null
+++ b/packages/api/src/routers/onboarding.ts
@@ -0,0 +1,119 @@
+import {
+ account,
+ db,
+ permission,
+ role,
+ rolePermission,
+ user,
+ userRole,
+} from "@minmon/db";
+import { hashCredentialPassword } from "@minmon/db/auth-utils";
+import { permissions, roleDefinitions } from "@minmon/db/rbac";
+import { TRPCError } from "@trpc/server";
+import { sql } from "drizzle-orm";
+
+import { publicProcedure, router } from "../index";
+import { onboardingCreateAdminSchema } from "./schemas";
+import { createEntityId } from "./utils";
+
+const ADMIN_ROLE_ID = "role_admin";
+
+export const onboardingRouter = router({
+ status: publicProcedure.query(async () => {
+ const [existingUser] = await db.select({ id: user.id }).from(user).limit(1);
+ return { needsSetup: !existingUser };
+ }),
+
+ createAdmin: publicProcedure
+ .input(onboardingCreateAdminSchema)
+ .mutation(async ({ input }) => {
+ const passwordHash = await hashCredentialPassword(input.password);
+ const userId = createEntityId();
+ const accountId = createEntityId();
+ const email = input.email.trim().toLowerCase();
+
+ return db.transaction(async (tx) => {
+ await tx.execute(sql`select pg_advisory_xact_lock(612984117)`);
+
+ const [existingUser] = await tx
+ .select({ id: user.id })
+ .from(user)
+ .limit(1);
+ if (existingUser) {
+ throw new TRPCError({
+ code: "CONFLICT",
+ message: "Minmon setup has already been completed",
+ });
+ }
+
+ const now = new Date();
+
+ await tx
+ .insert(permission)
+ .values(
+ permissions.map((name) => ({
+ id: name,
+ name,
+ description: `Allows ${name.replace(".", " ")}`,
+ createdAt: now,
+ updatedAt: now,
+ })),
+ )
+ .onConflictDoNothing();
+
+ await tx
+ .insert(role)
+ .values(
+ roleDefinitions.map((definition) => ({
+ id: definition.id,
+ name: definition.name,
+ description: definition.description,
+ createdAt: now,
+ updatedAt: now,
+ })),
+ )
+ .onConflictDoNothing();
+
+ await tx
+ .insert(rolePermission)
+ .values(
+ roleDefinitions.flatMap((definition) =>
+ definition.permissions.map((permissionName) => ({
+ roleId: definition.id,
+ permissionId: permissionName,
+ createdAt: now,
+ })),
+ ),
+ )
+ .onConflictDoNothing();
+
+ await tx.insert(user).values({
+ id: userId,
+ name: input.name,
+ email,
+ emailVerified: false,
+ mustChangePassword: false,
+ createdAt: now,
+ updatedAt: now,
+ });
+
+ await tx.insert(account).values({
+ id: accountId,
+ accountId: userId,
+ providerId: "credential",
+ userId,
+ password: passwordHash,
+ createdAt: now,
+ updatedAt: now,
+ });
+
+ await tx.insert(userRole).values({
+ userId,
+ roleId: ADMIN_ROLE_ID,
+ createdAt: now,
+ });
+
+ return { userId, email };
+ });
+ }),
+});
diff --git a/packages/api/src/routers/schemas.ts b/packages/api/src/routers/schemas.ts
index b69a4ec..ec79aef 100644
--- a/packages/api/src/routers/schemas.ts
+++ b/packages/api/src/routers/schemas.ts
@@ -10,7 +10,12 @@ export const ipv4Schema = z
"Must be a valid IPv4 address",
);
-export const optionalTextSchema = z.string().trim().max(5000).nullable().optional();
+export const optionalTextSchema = z
+ .string()
+ .trim()
+ .max(5000)
+ .nullable()
+ .optional();
export const hostnameSchema = z
.string()
@@ -23,10 +28,27 @@ export const hostnameSchema = z
);
export const serverStatusSchema = z.enum(["active", "maintenance", "inactive"]);
-export const serviceTypeSchema = z.enum(["web_app", "mail", "database", "api", "proxy", "other"]);
-export const serviceProtocolSchema = z.enum(["http", "https", "tcp", "udp", "other"]);
+export const serviceTypeSchema = z.enum([
+ "web_app",
+ "mail",
+ "database",
+ "api",
+ "proxy",
+ "other",
+]);
+export const serviceProtocolSchema = z.enum([
+ "http",
+ "https",
+ "tcp",
+ "udp",
+ "other",
+]);
export const serviceStatusSchema = z.enum(["active", "down", "maintenance"]);
-export const domainCheckStatusSchema = z.enum(["MATCH", "MISMATCH", "UNRESOLVED"]);
+export const domainCheckStatusSchema = z.enum([
+ "MATCH",
+ "MISMATCH",
+ "UNRESOLVED",
+]);
export const byIdSchema = z.object({
id: entityIdSchema,
@@ -114,6 +136,47 @@ export const updateUserRolesSchema = z.object({
export const userCreateSchema = z.object({
name: z.string().trim().min(2, "Name must be at least 2 characters").max(120),
email: z.email("Invalid email address").max(255),
- password: z.string().min(8, "Password must be at least 8 characters").max(255),
+ password: z
+ .string()
+ .min(8, "Password must be at least 8 characters")
+ .max(255),
roleIds: z.array(entityIdSchema).min(1, "Select at least one role"),
});
+
+export const onboardingCreateAdminSchema = z.object({
+ name: z.string().trim().min(2, "Name must be at least 2 characters").max(120),
+ email: z.email("Invalid email address").max(255),
+ password: z
+ .string()
+ .min(8, "Password must be at least 8 characters")
+ .max(255),
+});
+
+export const userInvitationCreateSchema = z.object({
+ roleIds: z.array(entityIdSchema).min(1, "Select at least one role"),
+});
+
+export const invitationTokenSchema = z.object({
+ token: z
+ .string()
+ .min(32, "Invalid invitation link")
+ .max(128, "Invalid invitation link")
+ .regex(/^[A-Za-z0-9_-]+$/, "Invalid invitation link"),
+});
+
+export const userInvitationAcceptSchema = invitationTokenSchema.extend({
+ name: z.string().trim().min(2, "Name must be at least 2 characters").max(120),
+ email: z.email("Invalid email address").max(255),
+ password: z
+ .string()
+ .min(8, "Password must be at least 8 characters")
+ .max(255),
+});
+
+export const changeInitialPasswordSchema = z.object({
+ currentPassword: z.string().min(1, "Enter your current password").max(255),
+ newPassword: z
+ .string()
+ .min(8, "Password must be at least 8 characters")
+ .max(255),
+});
diff --git a/packages/api/src/routers/users.ts b/packages/api/src/routers/users.ts
index 668f59f..95650ff 100644
--- a/packages/api/src/routers/users.ts
+++ b/packages/api/src/routers/users.ts
@@ -1,11 +1,42 @@
-import { db, account, role, user, userRole } from "@minmon/db";
+import { auth } from "@minmon/auth";
+import {
+ account,
+ db,
+ role,
+ session,
+ user,
+ userInvitation,
+ userInvitationRole,
+ userRole,
+} from "@minmon/db";
import { hashCredentialPassword } from "@minmon/db/auth-utils";
-import { asc, eq } from "drizzle-orm";
+import { TRPCError } from "@trpc/server";
+import { and, asc, count, desc, eq, isNull, ne, sql } from "drizzle-orm";
-import { permissionedProcedure, protectedProcedure, router } from "../index";
-import { byIdSchema, updateUserRolesSchema, userCreateSchema } from "./schemas";
+import {
+ createInvitationToken,
+ decryptInvitationToken,
+ hashInvitationToken,
+} from "../lib/invitation-token";
+import {
+ permissionedProcedure,
+ protectedProcedure,
+ publicProcedure,
+ router,
+} from "../index";
+import {
+ byIdSchema,
+ changeInitialPasswordSchema,
+ invitationTokenSchema,
+ updateUserRolesSchema,
+ userCreateSchema,
+ userInvitationAcceptSchema,
+ userInvitationCreateSchema,
+} from "./schemas";
import { badRequest, createEntityId, notFound } from "./utils";
+const ADMIN_ROLE_ID = "role_admin";
+
async function getUsersWithRoles() {
const [users, assignments] = await Promise.all([
db
@@ -14,6 +45,7 @@ async function getUsersWithRoles() {
name: user.name,
email: user.email,
emailVerified: user.emailVerified,
+ mustChangePassword: user.mustChangePassword,
image: user.image,
createdAt: user.createdAt,
updatedAt: user.updatedAt,
@@ -35,16 +67,84 @@ async function getUsersWithRoles() {
...item,
roles: assignments
.filter((assignment) => assignment.userId === item.id)
- .map((assignment) => ({ id: assignment.roleId, name: assignment.roleName })),
+ .map((assignment) => ({
+ id: assignment.roleId,
+ name: assignment.roleName,
+ })),
}));
}
+async function getInvitationsWithRoles() {
+ const [invitations, assignments] = await Promise.all([
+ db
+ .select({
+ id: userInvitation.id,
+ tokenEncrypted: userInvitation.tokenEncrypted,
+ tokenIv: userInvitation.tokenIv,
+ createdByUserId: userInvitation.createdByUserId,
+ acceptedUserId: userInvitation.acceptedUserId,
+ revokedAt: userInvitation.revokedAt,
+ acceptedAt: userInvitation.acceptedAt,
+ createdAt: userInvitation.createdAt,
+ updatedAt: userInvitation.updatedAt,
+ })
+ .from(userInvitation)
+ .orderBy(desc(userInvitation.createdAt), desc(userInvitation.id)),
+ db
+ .select({
+ invitationId: userInvitationRole.invitationId,
+ roleId: role.id,
+ roleName: role.name,
+ })
+ .from(userInvitationRole)
+ .innerJoin(role, eq(role.id, userInvitationRole.roleId))
+ .orderBy(asc(role.name)),
+ ]);
+
+ return Promise.all(
+ invitations.map(async (invitation) => {
+ const status = invitation.acceptedAt
+ ? ("accepted" as const)
+ : invitation.revokedAt
+ ? ("revoked" as const)
+ : ("pending" as const);
+ const token =
+ status === "pending"
+ ? await decryptInvitationToken(
+ invitation.tokenEncrypted,
+ invitation.tokenIv,
+ ).catch(() => null)
+ : null;
+
+ return {
+ id: invitation.id,
+ createdByUserId: invitation.createdByUserId,
+ acceptedUserId: invitation.acceptedUserId,
+ revokedAt: invitation.revokedAt,
+ acceptedAt: invitation.acceptedAt,
+ createdAt: invitation.createdAt,
+ updatedAt: invitation.updatedAt,
+ status,
+ token,
+ roles: assignments
+ .filter((assignment) => assignment.invitationId === invitation.id)
+ .map((assignment) => ({
+ id: assignment.roleId,
+ name: assignment.roleName,
+ })),
+ };
+ }),
+ );
+}
+
async function validateRoleIds(roleIds: string[]) {
const roles = await db.select({ id: role.id }).from(role);
const validRoleIds = new Set(roles.map((item) => item.id));
const uniqueRoleIds = Array.from(new Set(roleIds));
- const invalidRoleId = uniqueRoleIds.find((roleId) => !validRoleIds.has(roleId));
+ const invalidRoleId = uniqueRoleIds.find(
+ (roleId) => !validRoleIds.has(roleId),
+ );
if (invalidRoleId) {
notFound(`Role not found: ${invalidRoleId}`);
}
@@ -53,13 +153,26 @@ async function validateRoleIds(roleIds: string[]) {
}
export const usersRouter = router({
- me: protectedProcedure.query(({ ctx }) => ({
- user: ctx.session.user,
- roles: ctx.authorization.roles,
- permissions: ctx.authorization.permissions,
- })),
+ me: protectedProcedure.query(async ({ ctx }) => {
+ const [currentUser] = await db
+ .select({ mustChangePassword: user.mustChangePassword })
+ .from(user)
+ .where(eq(user.id, ctx.session.user.id))
+ .limit(1);
- list: permissionedProcedure("users.read").query(async () => getUsersWithRoles()),
+ return {
+ user: {
+ ...ctx.session.user,
+ mustChangePassword: currentUser?.mustChangePassword ?? false,
+ },
+ roles: ctx.authorization.roles,
+ permissions: ctx.authorization.permissions,
+ };
+ }),
+
+ list: permissionedProcedure("users.read").query(async () =>
+ getUsersWithRoles(),
+ ),
roles: permissionedProcedure("users.read").query(async () =>
db
@@ -75,7 +188,12 @@ export const usersRouter = router({
create: permissionedProcedure("users.create")
.input(userCreateSchema)
.mutation(async ({ input }) => {
- const [existingUser] = await db.select({ id: user.id }).from(user).where(eq(user.email, input.email)).limit(1);
+ const email = input.email.trim().toLowerCase();
+ const [existingUser] = await db
+ .select({ id: user.id })
+ .from(user)
+ .where(eq(sql`lower(${user.email})`, email))
+ .limit(1);
if (existingUser) {
badRequest("A user with this email already exists");
@@ -83,74 +201,429 @@ export const usersRouter = router({
const uniqueRoleIds = await validateRoleIds(input.roleIds);
const userId = createEntityId();
- const now = new Date();
const passwordHash = await hashCredentialPassword(input.password);
- await db.insert(user).values({
- id: userId,
- name: input.name,
- email: input.email,
- emailVerified: true,
- createdAt: now,
- updatedAt: now,
- });
+ await db.transaction(async (tx) => {
+ const now = new Date();
- await db.insert(account).values({
- id: createEntityId(),
- accountId: userId,
- providerId: "credential",
- userId,
- password: passwordHash,
- createdAt: now,
- updatedAt: now,
- });
+ await tx.insert(user).values({
+ id: userId,
+ name: input.name,
+ email,
+ emailVerified: false,
+ mustChangePassword: true,
+ createdAt: now,
+ updatedAt: now,
+ });
- await db.insert(userRole).values(
- uniqueRoleIds.map((roleId) => ({
+ await tx.insert(account).values({
+ id: createEntityId(),
+ accountId: userId,
+ providerId: "credential",
userId,
- roleId,
- })),
- );
+ password: passwordHash,
+ createdAt: now,
+ updatedAt: now,
+ });
+
+ await tx.insert(userRole).values(
+ uniqueRoleIds.map((roleId) => ({
+ userId,
+ roleId,
+ })),
+ );
+ });
const users = await getUsersWithRoles();
return users.find((item) => item.id === userId);
}),
+ invitations: router({
+ list: permissionedProcedure("users.create").query(async () =>
+ getInvitationsWithRoles(),
+ ),
+
+ create: permissionedProcedure("users.create")
+ .input(userInvitationCreateSchema)
+ .mutation(async ({ ctx, input }) => {
+ const uniqueRoleIds = await validateRoleIds(input.roleIds);
+ const invitationId = createEntityId();
+ const invitationToken = await createInvitationToken();
+
+ await db.transaction(async (tx) => {
+ const now = new Date();
+
+ await tx.insert(userInvitation).values({
+ id: invitationId,
+ tokenHash: invitationToken.tokenHash,
+ tokenEncrypted: invitationToken.tokenEncrypted,
+ tokenIv: invitationToken.tokenIv,
+ createdByUserId: ctx.session.user.id,
+ createdAt: now,
+ updatedAt: now,
+ });
+
+ await tx.insert(userInvitationRole).values(
+ uniqueRoleIds.map((roleId) => ({
+ invitationId,
+ roleId,
+ createdAt: now,
+ })),
+ );
+ });
+
+ const invitations = await getInvitationsWithRoles();
+ return invitations.find((invitation) => invitation.id === invitationId);
+ }),
+
+ revoke: permissionedProcedure("users.create")
+ .input(byIdSchema)
+ .mutation(async ({ input }) => {
+ const now = new Date();
+ const [revoked] = await db
+ .update(userInvitation)
+ .set({ revokedAt: now, updatedAt: now })
+ .where(
+ and(
+ eq(userInvitation.id, input.id),
+ isNull(userInvitation.revokedAt),
+ isNull(userInvitation.acceptedAt),
+ ),
+ )
+ .returning({ id: userInvitation.id });
+
+ if (!revoked) {
+ badRequest("Only a pending invitation can be revoked");
+ }
+
+ return { id: input.id };
+ }),
+
+ reissue: permissionedProcedure("users.create")
+ .input(byIdSchema)
+ .mutation(async ({ ctx, input }) => {
+ const invitationToken = await createInvitationToken();
+ const replacementId = createEntityId();
+
+ await db.transaction(async (tx) => {
+ const now = new Date();
+ const [replaced] = await tx
+ .update(userInvitation)
+ .set({ revokedAt: now, updatedAt: now })
+ .where(
+ and(
+ eq(userInvitation.id, input.id),
+ isNull(userInvitation.revokedAt),
+ isNull(userInvitation.acceptedAt),
+ ),
+ )
+ .returning({ id: userInvitation.id });
+
+ if (!replaced) {
+ badRequest("Only a pending invitation can be replaced");
+ }
+
+ const assignedRoles = await tx
+ .select({ roleId: userInvitationRole.roleId })
+ .from(userInvitationRole)
+ .where(eq(userInvitationRole.invitationId, input.id));
+
+ if (!assignedRoles.length) {
+ badRequest("The invitation has no roles to carry forward");
+ }
+
+ await tx.insert(userInvitation).values({
+ id: replacementId,
+ tokenHash: invitationToken.tokenHash,
+ tokenEncrypted: invitationToken.tokenEncrypted,
+ tokenIv: invitationToken.tokenIv,
+ createdByUserId: ctx.session.user.id,
+ createdAt: now,
+ updatedAt: now,
+ });
+
+ await tx.insert(userInvitationRole).values(
+ assignedRoles.map(({ roleId }) => ({
+ invitationId: replacementId,
+ roleId,
+ createdAt: now,
+ })),
+ );
+ });
+
+ const invitations = await getInvitationsWithRoles();
+ return invitations.find(
+ (invitation) => invitation.id === replacementId,
+ );
+ }),
+
+ inspect: publicProcedure
+ .input(invitationTokenSchema)
+ .query(async ({ input }) => {
+ const tokenHash = await hashInvitationToken(input.token);
+ const [invitation] = await db
+ .select({
+ id: userInvitation.id,
+ revokedAt: userInvitation.revokedAt,
+ acceptedAt: userInvitation.acceptedAt,
+ })
+ .from(userInvitation)
+ .where(eq(userInvitation.tokenHash, tokenHash))
+ .limit(1);
+
+ if (!invitation) {
+ return { status: "invalid" as const, roles: [] };
+ }
+
+ const assignedRoles = await db
+ .select({ id: role.id, name: role.name })
+ .from(userInvitationRole)
+ .innerJoin(role, eq(role.id, userInvitationRole.roleId))
+ .where(eq(userInvitationRole.invitationId, invitation.id))
+ .orderBy(asc(role.name));
+
+ return {
+ status: invitation.acceptedAt
+ ? ("accepted" as const)
+ : invitation.revokedAt
+ ? ("revoked" as const)
+ : ("pending" as const),
+ roles: assignedRoles,
+ };
+ }),
+
+ accept: publicProcedure
+ .input(userInvitationAcceptSchema)
+ .mutation(async ({ input }) => {
+ const tokenHash = await hashInvitationToken(input.token);
+ const [activeInvitation] = await db
+ .select({ id: userInvitation.id })
+ .from(userInvitation)
+ .where(
+ and(
+ eq(userInvitation.tokenHash, tokenHash),
+ isNull(userInvitation.revokedAt),
+ isNull(userInvitation.acceptedAt),
+ ),
+ )
+ .limit(1);
+
+ if (!activeInvitation) {
+ badRequest("This invitation link is invalid or no longer active");
+ }
+
+ const email = input.email.trim().toLowerCase();
+ const passwordHash = await hashCredentialPassword(input.password);
+ const userId = createEntityId();
+
+ await db.transaction(async (tx) => {
+ const now = new Date();
+ const [claimedInvitation] = await tx
+ .update(userInvitation)
+ .set({ acceptedAt: now, updatedAt: now })
+ .where(
+ and(
+ eq(userInvitation.tokenHash, tokenHash),
+ isNull(userInvitation.revokedAt),
+ isNull(userInvitation.acceptedAt),
+ ),
+ )
+ .returning({ id: userInvitation.id });
+
+ if (!claimedInvitation) {
+ badRequest("This invitation link has already been used or revoked");
+ }
+
+ const assignedRoles = await tx
+ .select({ roleId: userInvitationRole.roleId })
+ .from(userInvitationRole)
+ .where(eq(userInvitationRole.invitationId, claimedInvitation.id));
+
+ if (!assignedRoles.length) {
+ badRequest("This invitation no longer grants an access role");
+ }
+
+ const [existingUser] = await tx
+ .select({ id: user.id })
+ .from(user)
+ .where(eq(sql`lower(${user.email})`, email))
+ .limit(1);
+
+ if (existingUser) {
+ badRequest("A user with this email already exists");
+ }
+
+ await tx.insert(user).values({
+ id: userId,
+ name: input.name,
+ email,
+ emailVerified: false,
+ mustChangePassword: false,
+ createdAt: now,
+ updatedAt: now,
+ });
+
+ await tx.insert(account).values({
+ id: createEntityId(),
+ accountId: userId,
+ providerId: "credential",
+ userId,
+ password: passwordHash,
+ createdAt: now,
+ updatedAt: now,
+ });
+
+ await tx.insert(userRole).values(
+ assignedRoles.map(({ roleId }) => ({
+ userId,
+ roleId,
+ createdAt: now,
+ })),
+ );
+
+ await tx
+ .update(userInvitation)
+ .set({ acceptedUserId: userId, updatedAt: now })
+ .where(eq(userInvitation.id, claimedInvitation.id));
+ });
+
+ return { userId, email };
+ }),
+ }),
+
updateRoles: permissionedProcedure("users.assignRoles")
.input(updateUserRolesSchema)
.mutation(async ({ input }) => {
- const [existingUser] = await db.select({ id: user.id }).from(user).where(eq(user.id, input.userId)).limit(1);
-
- if (!existingUser) {
- notFound("User not found");
- }
-
const uniqueRoleIds = await validateRoleIds(input.roleIds);
- await db.delete(userRole).where(eq(userRole.userId, input.userId));
- await db.insert(userRole).values(
- uniqueRoleIds.map((roleId) => ({
- userId: input.userId,
- roleId,
- })),
- );
+ await db.transaction(async (tx) => {
+ await tx.execute(sql`select pg_advisory_xact_lock(612984119)`);
+
+ const [existingUser] = await tx
+ .select({ id: user.id })
+ .from(user)
+ .where(eq(user.id, input.userId))
+ .limit(1);
+
+ if (!existingUser) {
+ notFound("User not found");
+ }
+
+ const existingRoles = await tx
+ .select({ roleId: userRole.roleId })
+ .from(userRole)
+ .where(eq(userRole.userId, input.userId));
+ const removesAdmin =
+ existingRoles.some(({ roleId }) => roleId === ADMIN_ROLE_ID) &&
+ !uniqueRoleIds.includes(ADMIN_ROLE_ID);
+
+ if (removesAdmin) {
+ const [adminCount] = await tx
+ .select({ value: count() })
+ .from(userRole)
+ .where(eq(userRole.roleId, ADMIN_ROLE_ID));
+
+ if ((adminCount?.value ?? 0) <= 1) {
+ badRequest("Minmon must always have at least one administrator");
+ }
+ }
+
+ await tx.delete(userRole).where(eq(userRole.userId, input.userId));
+ await tx.insert(userRole).values(
+ uniqueRoleIds.map((roleId) => ({
+ userId: input.userId,
+ roleId,
+ })),
+ );
+ });
const updated = await getUsersWithRoles();
return updated.find((item) => item.id === input.userId);
}),
- delete: permissionedProcedure("users.delete").input(byIdSchema).mutation(async ({ ctx, input }) => {
- if (ctx.session.user.id === input.id) {
- badRequest("You cannot delete your own user account while signed in");
- }
+ changeInitialPassword: protectedProcedure
+ .input(changeInitialPasswordSchema)
+ .mutation(async ({ ctx, input }) => {
+ try {
+ await auth.api.changePassword({
+ body: {
+ currentPassword: input.currentPassword,
+ newPassword: input.newPassword,
+ revokeOtherSessions: false,
+ },
+ headers: ctx.requestHeaders,
+ });
+ } catch {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message:
+ "The current password is incorrect or the new password is invalid",
+ });
+ }
- const [existingUser] = await db.select({ id: user.id }).from(user).where(eq(user.id, input.id)).limit(1);
+ await db.transaction(async (tx) => {
+ await tx
+ .update(user)
+ .set({ mustChangePassword: false, updatedAt: new Date() })
+ .where(eq(user.id, ctx.session.user.id));
+ await tx
+ .delete(session)
+ .where(
+ and(
+ eq(session.userId, ctx.session.user.id),
+ ne(session.id, ctx.session.session.id),
+ ),
+ );
+ });
- if (!existingUser) {
- notFound("User not found");
- }
+ return { status: true };
+ }),
- await db.delete(user).where(eq(user.id, input.id));
- return { id: input.id };
- }),
+ delete: permissionedProcedure("users.delete")
+ .input(byIdSchema)
+ .mutation(async ({ ctx, input }) => {
+ if (ctx.session.user.id === input.id) {
+ badRequest("You cannot delete your own user account while signed in");
+ }
+
+ await db.transaction(async (tx) => {
+ await tx.execute(sql`select pg_advisory_xact_lock(612984119)`);
+
+ const [existingUser] = await tx
+ .select({ id: user.id })
+ .from(user)
+ .where(eq(user.id, input.id))
+ .limit(1);
+
+ if (!existingUser) {
+ notFound("User not found");
+ }
+
+ const [adminRole] = await tx
+ .select({ roleId: userRole.roleId })
+ .from(userRole)
+ .where(
+ and(
+ eq(userRole.userId, input.id),
+ eq(userRole.roleId, ADMIN_ROLE_ID),
+ ),
+ )
+ .limit(1);
+
+ if (adminRole) {
+ const [adminCount] = await tx
+ .select({ value: count() })
+ .from(userRole)
+ .where(eq(userRole.roleId, ADMIN_ROLE_ID));
+
+ if ((adminCount?.value ?? 0) <= 1) {
+ badRequest("The last administrator cannot be deleted");
+ }
+ }
+
+ await tx.delete(user).where(eq(user.id, input.id));
+ });
+
+ return { id: input.id };
+ }),
});
diff --git a/packages/auth/src/index.ts b/packages/auth/src/index.ts
index 9d1b584..a623dd6 100644
--- a/packages/auth/src/index.ts
+++ b/packages/auth/src/index.ts
@@ -17,6 +17,17 @@ export function createAuth() {
trustedOrigins: [env.CORS_ORIGIN],
emailAndPassword: {
enabled: true,
+ disableSignUp: true,
+ },
+ user: {
+ additionalFields: {
+ mustChangePassword: {
+ type: "boolean",
+ required: false,
+ defaultValue: false,
+ input: false,
+ },
+ },
},
secret: env.BETTER_AUTH_SECRET,
baseURL: env.BETTER_AUTH_URL,
diff --git a/packages/db/src/migrations/0004_lean_jazinda.sql b/packages/db/src/migrations/0004_lean_jazinda.sql
new file mode 100644
index 0000000..124ebc6
--- /dev/null
+++ b/packages/db/src/migrations/0004_lean_jazinda.sql
@@ -0,0 +1,40 @@
+ALTER TABLE "user" ADD COLUMN "must_change_password" boolean DEFAULT false NOT NULL;
+--> statement-breakpoint
+CREATE TABLE "user_invitation" (
+ "id" text PRIMARY KEY NOT NULL,
+ "token_hash" text NOT NULL,
+ "token_encrypted" text NOT NULL,
+ "token_iv" text NOT NULL,
+ "created_by_user_id" text,
+ "accepted_user_id" text,
+ "revoked_at" timestamp,
+ "accepted_at" timestamp,
+ "created_at" timestamp DEFAULT now() NOT NULL,
+ "updated_at" timestamp DEFAULT now() NOT NULL,
+ CONSTRAINT "user_invitation_token_hash_unique" UNIQUE("token_hash")
+);
+--> statement-breakpoint
+CREATE TABLE "user_invitation_role" (
+ "invitation_id" text NOT NULL,
+ "role_id" text NOT NULL,
+ "created_at" timestamp DEFAULT now() NOT NULL,
+ CONSTRAINT "user_invitation_role_invitation_id_role_id_pk" PRIMARY KEY("invitation_id","role_id")
+);
+--> statement-breakpoint
+ALTER TABLE "user_invitation" ADD CONSTRAINT "user_invitation_created_by_user_id_user_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;
+--> statement-breakpoint
+ALTER TABLE "user_invitation" ADD CONSTRAINT "user_invitation_accepted_user_id_user_id_fk" FOREIGN KEY ("accepted_user_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;
+--> statement-breakpoint
+ALTER TABLE "user_invitation_role" ADD CONSTRAINT "user_invitation_role_invitation_id_user_invitation_id_fk" FOREIGN KEY ("invitation_id") REFERENCES "public"."user_invitation"("id") ON DELETE cascade ON UPDATE no action;
+--> statement-breakpoint
+ALTER TABLE "user_invitation_role" ADD CONSTRAINT "user_invitation_role_role_id_role_id_fk" FOREIGN KEY ("role_id") REFERENCES "public"."role"("id") ON DELETE cascade ON UPDATE no action;
+--> statement-breakpoint
+CREATE INDEX "user_invitation_created_by_user_id_idx" ON "user_invitation" USING btree ("created_by_user_id");
+--> statement-breakpoint
+CREATE INDEX "user_invitation_accepted_user_id_idx" ON "user_invitation" USING btree ("accepted_user_id");
+--> statement-breakpoint
+CREATE INDEX "user_invitation_created_at_idx" ON "user_invitation" USING btree ("created_at");
+--> statement-breakpoint
+CREATE INDEX "user_invitation_role_invitation_id_idx" ON "user_invitation_role" USING btree ("invitation_id");
+--> statement-breakpoint
+CREATE INDEX "user_invitation_role_role_id_idx" ON "user_invitation_role" USING btree ("role_id");
diff --git a/packages/db/src/migrations/meta/0004_snapshot.json b/packages/db/src/migrations/meta/0004_snapshot.json
new file mode 100644
index 0000000..9a8d920
--- /dev/null
+++ b/packages/db/src/migrations/meta/0004_snapshot.json
@@ -0,0 +1,1625 @@
+{
+ "id": "ef5968f8-67fb-4a82-8b4b-0ab44672f2db",
+ "prevId": "86aed547-2dfd-44fb-a831-d9c72fec17fb",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.account": {
+ "name": "account",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "account_id": {
+ "name": "account_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "provider_id": {
+ "name": "provider_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "access_token_expires_at": {
+ "name": "access_token_expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refresh_token_expires_at": {
+ "name": "refresh_token_expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "account_userId_idx": {
+ "name": "account_userId_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "account_user_id_user_id_fk": {
+ "name": "account_user_id_user_id_fk",
+ "tableFrom": "account",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.permission": {
+ "name": "permission",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "permission_name_unique": {
+ "name": "permission_name_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "name"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.role": {
+ "name": "role",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "role_name_unique": {
+ "name": "role_name_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "name"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.role_permission": {
+ "name": "role_permission",
+ "schema": "",
+ "columns": {
+ "role_id": {
+ "name": "role_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "permission_id": {
+ "name": "permission_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "role_permission_role_id_idx": {
+ "name": "role_permission_role_id_idx",
+ "columns": [
+ {
+ "expression": "role_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "role_permission_permission_id_idx": {
+ "name": "role_permission_permission_id_idx",
+ "columns": [
+ {
+ "expression": "permission_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "role_permission_role_id_role_id_fk": {
+ "name": "role_permission_role_id_role_id_fk",
+ "tableFrom": "role_permission",
+ "tableTo": "role",
+ "columnsFrom": [
+ "role_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "role_permission_permission_id_permission_id_fk": {
+ "name": "role_permission_permission_id_permission_id_fk",
+ "tableFrom": "role_permission",
+ "tableTo": "permission",
+ "columnsFrom": [
+ "permission_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "role_permission_role_id_permission_id_pk": {
+ "name": "role_permission_role_id_permission_id_pk",
+ "columns": [
+ "role_id",
+ "permission_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.session": {
+ "name": "session",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "ip_address": {
+ "name": "ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "session_userId_idx": {
+ "name": "session_userId_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "session_user_id_user_id_fk": {
+ "name": "session_user_id_user_id_fk",
+ "tableFrom": "session",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "session_token_unique": {
+ "name": "session_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user": {
+ "name": "user",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email_verified": {
+ "name": "email_verified",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "must_change_password": {
+ "name": "must_change_password",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_email_unique": {
+ "name": "user_email_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "email"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_invitation": {
+ "name": "user_invitation",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "token_hash": {
+ "name": "token_hash",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token_encrypted": {
+ "name": "token_encrypted",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token_iv": {
+ "name": "token_iv",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_by_user_id": {
+ "name": "created_by_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accepted_user_id": {
+ "name": "accepted_user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "revoked_at": {
+ "name": "revoked_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accepted_at": {
+ "name": "accepted_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_invitation_created_by_user_id_idx": {
+ "name": "user_invitation_created_by_user_id_idx",
+ "columns": [
+ {
+ "expression": "created_by_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_invitation_accepted_user_id_idx": {
+ "name": "user_invitation_accepted_user_id_idx",
+ "columns": [
+ {
+ "expression": "accepted_user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_invitation_created_at_idx": {
+ "name": "user_invitation_created_at_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_invitation_created_by_user_id_user_id_fk": {
+ "name": "user_invitation_created_by_user_id_user_id_fk",
+ "tableFrom": "user_invitation",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "user_invitation_accepted_user_id_user_id_fk": {
+ "name": "user_invitation_accepted_user_id_user_id_fk",
+ "tableFrom": "user_invitation",
+ "tableTo": "user",
+ "columnsFrom": [
+ "accepted_user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_invitation_token_hash_unique": {
+ "name": "user_invitation_token_hash_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token_hash"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_invitation_role": {
+ "name": "user_invitation_role",
+ "schema": "",
+ "columns": {
+ "invitation_id": {
+ "name": "invitation_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role_id": {
+ "name": "role_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_invitation_role_invitation_id_idx": {
+ "name": "user_invitation_role_invitation_id_idx",
+ "columns": [
+ {
+ "expression": "invitation_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_invitation_role_role_id_idx": {
+ "name": "user_invitation_role_role_id_idx",
+ "columns": [
+ {
+ "expression": "role_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_invitation_role_invitation_id_user_invitation_id_fk": {
+ "name": "user_invitation_role_invitation_id_user_invitation_id_fk",
+ "tableFrom": "user_invitation_role",
+ "tableTo": "user_invitation",
+ "columnsFrom": [
+ "invitation_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_invitation_role_role_id_role_id_fk": {
+ "name": "user_invitation_role_role_id_role_id_fk",
+ "tableFrom": "user_invitation_role",
+ "tableTo": "role",
+ "columnsFrom": [
+ "role_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "user_invitation_role_invitation_id_role_id_pk": {
+ "name": "user_invitation_role_invitation_id_role_id_pk",
+ "columns": [
+ "invitation_id",
+ "role_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_role": {
+ "name": "user_role",
+ "schema": "",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role_id": {
+ "name": "role_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_role_user_id_idx": {
+ "name": "user_role_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_role_role_id_idx": {
+ "name": "user_role_role_id_idx",
+ "columns": [
+ {
+ "expression": "role_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_role_user_id_user_id_fk": {
+ "name": "user_role_user_id_user_id_fk",
+ "tableFrom": "user_role",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "user_role_role_id_role_id_fk": {
+ "name": "user_role_role_id_role_id_fk",
+ "tableFrom": "user_role",
+ "tableTo": "role",
+ "columnsFrom": [
+ "role_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "user_role_user_id_role_id_pk": {
+ "name": "user_role_user_id_role_id_pk",
+ "columns": [
+ "user_id",
+ "role_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verification": {
+ "name": "verification",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "verification_identifier_idx": {
+ "name": "verification_identifier_idx",
+ "columns": [
+ {
+ "expression": "identifier",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.domain": {
+ "name": "domain",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "service_id": {
+ "name": "service_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expected_server_ip": {
+ "name": "expected_server_ip",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "last_resolved_ip": {
+ "name": "last_resolved_ip",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_resolved_ips": {
+ "name": "last_resolved_ips",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "resolution_status": {
+ "name": "resolution_status",
+ "type": "domain_resolution_status",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'UNRESOLVED'"
+ },
+ "last_checked_at": {
+ "name": "last_checked_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "remarks": {
+ "name": "remarks",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "last_check_message": {
+ "name": "last_check_message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "domain_name_unique": {
+ "name": "domain_name_unique",
+ "columns": [
+ {
+ "expression": "name",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "domain_service_id_idx": {
+ "name": "domain_service_id_idx",
+ "columns": [
+ {
+ "expression": "service_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "domain_resolution_status_idx": {
+ "name": "domain_resolution_status_idx",
+ "columns": [
+ {
+ "expression": "resolution_status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "domain_service_id_service_id_fk": {
+ "name": "domain_service_id_service_id_fk",
+ "tableFrom": "domain",
+ "tableTo": "service",
+ "columnsFrom": [
+ "service_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.domain_check_history": {
+ "name": "domain_check_history",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "domain_id": {
+ "name": "domain_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expected_server_ip": {
+ "name": "expected_server_ip",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "domain_resolution_status",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "resolved_ips": {
+ "name": "resolved_ips",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "checked_at": {
+ "name": "checked_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "domain_check_history_domain_id_idx": {
+ "name": "domain_check_history_domain_id_idx",
+ "columns": [
+ {
+ "expression": "domain_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "domain_check_history_checked_at_idx": {
+ "name": "domain_check_history_checked_at_idx",
+ "columns": [
+ {
+ "expression": "checked_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "domain_check_history_status_idx": {
+ "name": "domain_check_history_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "domain_check_history_domain_id_domain_id_fk": {
+ "name": "domain_check_history_domain_id_domain_id_fk",
+ "tableFrom": "domain_check_history",
+ "tableTo": "domain",
+ "columnsFrom": [
+ "domain_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.note": {
+ "name": "note",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "server_id": {
+ "name": "server_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "category": {
+ "name": "category",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "note_server_id_idx": {
+ "name": "note_server_id_idx",
+ "columns": [
+ {
+ "expression": "server_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "note_category_idx": {
+ "name": "note_category_idx",
+ "columns": [
+ {
+ "expression": "category",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "note_server_id_server_id_fk": {
+ "name": "note_server_id_server_id_fk",
+ "tableFrom": "note",
+ "tableTo": "server",
+ "columnsFrom": [
+ "server_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.server": {
+ "name": "server",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "primary_ip_address": {
+ "name": "primary_ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "secondary_ip_address": {
+ "name": "secondary_ip_address",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "operating_system": {
+ "name": "operating_system",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "location": {
+ "name": "location",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "server_status",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'active'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "server_name_unique": {
+ "name": "server_name_unique",
+ "columns": [
+ {
+ "expression": "name",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "server_status_idx": {
+ "name": "server_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.service": {
+ "name": "service",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "server_id": {
+ "name": "server_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "service_type",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'other'"
+ },
+ "internal_port": {
+ "name": "internal_port",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "external_port": {
+ "name": "external_port",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "protocol": {
+ "name": "protocol",
+ "type": "service_protocol",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'http'"
+ },
+ "status": {
+ "name": "status",
+ "type": "service_status",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'active'"
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "service_server_id_idx": {
+ "name": "service_server_id_idx",
+ "columns": [
+ {
+ "expression": "server_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "service_status_idx": {
+ "name": "service_status_idx",
+ "columns": [
+ {
+ "expression": "status",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "service_server_name_unique": {
+ "name": "service_server_name_unique",
+ "columns": [
+ {
+ "expression": "server_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "name",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "service_server_id_server_id_fk": {
+ "name": "service_server_id_server_id_fk",
+ "tableFrom": "service",
+ "tableTo": "server",
+ "columnsFrom": [
+ "server_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {
+ "public.domain_resolution_status": {
+ "name": "domain_resolution_status",
+ "schema": "public",
+ "values": [
+ "MATCH",
+ "MISMATCH",
+ "UNRESOLVED"
+ ]
+ },
+ "public.server_status": {
+ "name": "server_status",
+ "schema": "public",
+ "values": [
+ "active",
+ "maintenance",
+ "inactive"
+ ]
+ },
+ "public.service_protocol": {
+ "name": "service_protocol",
+ "schema": "public",
+ "values": [
+ "http",
+ "https",
+ "tcp",
+ "udp",
+ "other"
+ ]
+ },
+ "public.service_status": {
+ "name": "service_status",
+ "schema": "public",
+ "values": [
+ "active",
+ "down",
+ "maintenance"
+ ]
+ },
+ "public.service_type": {
+ "name": "service_type",
+ "schema": "public",
+ "values": [
+ "web_app",
+ "mail",
+ "database",
+ "api",
+ "proxy",
+ "other"
+ ]
+ }
+ },
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
\ No newline at end of file
diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json
index 125a618..2fc7338 100644
--- a/packages/db/src/migrations/meta/_journal.json
+++ b/packages/db/src/migrations/meta/_journal.json
@@ -29,6 +29,13 @@
"when": 1786104000000,
"tag": "0003_add_domain_check_history",
"breakpoints": true
+ },
+ {
+ "idx": 4,
+ "version": "7",
+ "when": 1786105359203,
+ "tag": "0004_lean_jazinda",
+ "breakpoints": true
}
]
-}
+}
\ No newline at end of file
diff --git a/packages/db/src/schema/auth.ts b/packages/db/src/schema/auth.ts
index cf4ab35..199c25c 100644
--- a/packages/db/src/schema/auth.ts
+++ b/packages/db/src/schema/auth.ts
@@ -1,11 +1,19 @@
import { relations } from "drizzle-orm";
-import { pgTable, text, timestamp, boolean, index, primaryKey } from "drizzle-orm/pg-core";
+import {
+ pgTable,
+ text,
+ timestamp,
+ boolean,
+ index,
+ primaryKey,
+} from "drizzle-orm/pg-core";
export const user = pgTable("user", {
id: text("id").primaryKey(),
name: text("name").notNull(),
email: text("email").notNull().unique(),
emailVerified: boolean("email_verified").default(false).notNull(),
+ mustChangePassword: boolean("must_change_password").default(false).notNull(),
image: text("image"),
createdAt: timestamp("created_at").defaultNow().notNull(),
updatedAt: timestamp("updated_at")
@@ -131,10 +139,62 @@ export const userRole = pgTable(
],
);
+export const userInvitation = pgTable(
+ "user_invitation",
+ {
+ id: text("id").primaryKey(),
+ tokenHash: text("token_hash").notNull().unique(),
+ tokenEncrypted: text("token_encrypted").notNull(),
+ tokenIv: text("token_iv").notNull(),
+ createdByUserId: text("created_by_user_id").references(() => user.id, {
+ onDelete: "set null",
+ }),
+ acceptedUserId: text("accepted_user_id").references(() => user.id, {
+ onDelete: "set null",
+ }),
+ revokedAt: timestamp("revoked_at"),
+ acceptedAt: timestamp("accepted_at"),
+ createdAt: timestamp("created_at").defaultNow().notNull(),
+ updatedAt: timestamp("updated_at")
+ .defaultNow()
+ .$onUpdate(() => /* @__PURE__ */ new Date())
+ .notNull(),
+ },
+ (table) => [
+ index("user_invitation_created_by_user_id_idx").on(table.createdByUserId),
+ index("user_invitation_accepted_user_id_idx").on(table.acceptedUserId),
+ index("user_invitation_created_at_idx").on(table.createdAt),
+ ],
+);
+
+export const userInvitationRole = pgTable(
+ "user_invitation_role",
+ {
+ invitationId: text("invitation_id")
+ .notNull()
+ .references(() => userInvitation.id, { onDelete: "cascade" }),
+ roleId: text("role_id")
+ .notNull()
+ .references(() => role.id, { onDelete: "cascade" }),
+ createdAt: timestamp("created_at").defaultNow().notNull(),
+ },
+ (table) => [
+ primaryKey({ columns: [table.invitationId, table.roleId] }),
+ index("user_invitation_role_invitation_id_idx").on(table.invitationId),
+ index("user_invitation_role_role_id_idx").on(table.roleId),
+ ],
+);
+
export const userRelations = relations(user, ({ many }) => ({
sessions: many(session),
accounts: many(account),
roles: many(userRole),
+ createdInvitations: many(userInvitation, {
+ relationName: "invitationCreator",
+ }),
+ acceptedInvitations: many(userInvitation, {
+ relationName: "invitationRecipient",
+ }),
}));
export const sessionRelations = relations(session, ({ one }) => ({
@@ -181,3 +241,34 @@ export const userRoleRelations = relations(userRole, ({ one }) => ({
references: [role.id],
}),
}));
+
+export const userInvitationRelations = relations(
+ userInvitation,
+ ({ one, many }) => ({
+ createdBy: one(user, {
+ fields: [userInvitation.createdByUserId],
+ references: [user.id],
+ relationName: "invitationCreator",
+ }),
+ acceptedUser: one(user, {
+ fields: [userInvitation.acceptedUserId],
+ references: [user.id],
+ relationName: "invitationRecipient",
+ }),
+ roles: many(userInvitationRole),
+ }),
+);
+
+export const userInvitationRoleRelations = relations(
+ userInvitationRole,
+ ({ one }) => ({
+ invitation: one(userInvitation, {
+ fields: [userInvitationRole.invitationId],
+ references: [userInvitation.id],
+ }),
+ role: one(role, {
+ fields: [userInvitationRole.roleId],
+ references: [role.id],
+ }),
+ }),
+);
diff --git a/packages/db/src/seed-if-empty.ts b/packages/db/src/seed-if-empty.ts
index 9a6112b..ff4f94b 100644
--- a/packages/db/src/seed-if-empty.ts
+++ b/packages/db/src/seed-if-empty.ts
@@ -4,25 +4,13 @@ dotenv.config({
path: new URL("../../../apps/server/.env", import.meta.url).pathname,
});
-import { db } from "./index";
-import { seed, seedRolesAndPermissions } from "./seed";
+import { seedRolesAndPermissions } from "./seed";
async function seedIfEmpty() {
- const existingUser = await db.query.user.findFirst({
- columns: {
- id: true,
- },
- });
-
- if (existingUser) {
- await seedRolesAndPermissions(existingUser.id);
- console.info("Database already has users; ensured default roles and permissions.");
- return;
- }
-
- await seed();
- console.info("Seeded auth admin and monitoring dashboard sample data.");
- console.info("Admin login: admin@minmon.local / admin12345");
+ await seedRolesAndPermissions();
+ console.info(
+ "Ensured default roles and permissions. First-run setup will create the administrator.",
+ );
}
seedIfEmpty()
diff --git a/packages/db/src/seed.ts b/packages/db/src/seed.ts
index da5da02..ce90040 100644
--- a/packages/db/src/seed.ts
+++ b/packages/db/src/seed.ts
@@ -7,8 +7,21 @@ dotenv.config({
});
import { db } from "./index";
-import { account, permission, role, rolePermission, user, userRole } from "./schema/auth";
-import { domain, domainCheckHistory, note, server, service } from "./schema/monitoring";
+import {
+ account,
+ permission,
+ role,
+ rolePermission,
+ user,
+ userRole,
+} from "./schema/auth";
+import {
+ domain,
+ domainCheckHistory,
+ note,
+ server,
+ service,
+} from "./schema/monitoring";
const now = new Date();
const earlierToday = new Date(now.getTime() - 45 * 60 * 1000);
@@ -30,7 +43,8 @@ const servers = [
operatingSystem: "Ubuntu 24.04 LTS",
location: "Singapore",
provider: "DigitalOcean",
- description: "Main production server hosting the dashboard web app, API, and reverse proxy.",
+ description:
+ "Main production server hosting the dashboard web app, API, and reverse proxy.",
status: "active" as const,
},
{
@@ -52,7 +66,8 @@ const servers = [
operatingSystem: "Ubuntu 22.04 LTS",
location: "Campus Lab",
provider: "University Lab",
- description: "Used for student practice and lecturer demonstration in class.",
+ description:
+ "Used for student practice and lecturer demonstration in class.",
status: "inactive" as const,
},
];
@@ -67,7 +82,8 @@ const services = [
externalPort: 443,
protocol: "https" as const,
status: "active" as const,
- description: "Frontend application for the private server management dashboard.",
+ description:
+ "Frontend application for the private server management dashboard.",
},
{
id: "service_dashboard_api",
@@ -89,7 +105,8 @@ const services = [
externalPort: 25,
protocol: "tcp" as const,
status: "maintenance" as const,
- description: "Mail service used as a sample SMTP gateway for the assignment.",
+ description:
+ "Mail service used as a sample SMTP gateway for the assignment.",
},
{
id: "service_lab_proxy",
@@ -100,7 +117,8 @@ const services = [
externalPort: 80,
protocol: "http" as const,
status: "down" as const,
- description: "Reverse proxy for local practice deployments in the campus lab.",
+ description:
+ "Reverse proxy for local practice deployments in the campus lab.",
},
];
@@ -151,7 +169,8 @@ const domains = [
resolutionStatus: "UNRESOLVED" as const,
lastCheckedAt: yesterday,
remarks: "Lab VM is powered off outside teaching hours.",
- lastCheckMessage: "DNS lookup failed because the host could not be resolved.",
+ lastCheckMessage:
+ "DNS lookup failed because the host could not be resolved.",
},
];
@@ -160,7 +179,8 @@ const notes = [
id: "note_prod_backup",
serverId: "server_prod_1",
title: "Weekly backup reminder",
- content: "Verify the PostgreSQL backup every Friday before the lecturer demo session.",
+ content:
+ "Verify the PostgreSQL backup every Friday before the lecturer demo session.",
category: "maintenance",
},
{
@@ -175,14 +195,16 @@ const notes = [
id: "note_mail_dns",
serverId: "server_mail_1",
title: "Update stale A record",
- content: "Point mail.minmon.dev to the current mail server before final presentation week.",
+ content:
+ "Point mail.minmon.dev to the current mail server before final presentation week.",
category: "todo",
},
{
id: "note_lab_status",
serverId: "server_lab_1",
title: "Lab VM inactive",
- content: "The campus lab VM is intentionally inactive outside class hours, so related checks may fail.",
+ content:
+ "The campus lab VM is intentionally inactive outside class hours, so related checks may fail.",
category: "incident",
},
];
@@ -202,7 +224,8 @@ async function seedAuthAdmin() {
id: adminUser.id,
name: adminUser.name,
email: adminUser.email,
- emailVerified: true,
+ emailVerified: false,
+ mustChangePassword: false,
createdAt: now,
updatedAt: now,
});
@@ -221,42 +244,54 @@ async function seedAuthAdmin() {
}
export async function seedRolesAndPermissions(adminUserId?: string) {
- await db.insert(permission).values(
- permissions.map((name) => ({
- id: name,
- name,
- description: `Allows ${name.replace(".", " ")}`,
- createdAt: now,
- updatedAt: now,
- })),
- ).onConflictDoNothing();
-
- await db.insert(role).values(
- roleDefinitions.map((item) => ({
- id: item.id,
- name: item.name,
- description: item.description,
- createdAt: now,
- updatedAt: now,
- })),
- ).onConflictDoNothing();
-
- await db.insert(rolePermission).values(
- roleDefinitions.flatMap((item) =>
- item.permissions.map((permissionName) => ({
- roleId: item.id,
- permissionId: permissionName,
+ await db
+ .insert(permission)
+ .values(
+ permissions.map((name) => ({
+ id: name,
+ name,
+ description: `Allows ${name.replace(".", " ")}`,
createdAt: now,
+ updatedAt: now,
})),
- ),
- ).onConflictDoNothing();
+ )
+ .onConflictDoNothing();
+
+ await db
+ .insert(role)
+ .values(
+ roleDefinitions.map((item) => ({
+ id: item.id,
+ name: item.name,
+ description: item.description,
+ createdAt: now,
+ updatedAt: now,
+ })),
+ )
+ .onConflictDoNothing();
+
+ await db
+ .insert(rolePermission)
+ .values(
+ roleDefinitions.flatMap((item) =>
+ item.permissions.map((permissionName) => ({
+ roleId: item.id,
+ permissionId: permissionName,
+ createdAt: now,
+ })),
+ ),
+ )
+ .onConflictDoNothing();
if (adminUserId) {
- await db.insert(userRole).values({
- userId: adminUserId,
- roleId: "role_admin",
- createdAt: now,
- }).onConflictDoNothing();
+ await db
+ .insert(userRole)
+ .values({
+ userId: adminUserId,
+ roleId: "role_admin",
+ createdAt: now,
+ })
+ .onConflictDoNothing();
}
}
diff --git a/packages/ui/src/components/alert.tsx b/packages/ui/src/components/alert.tsx
new file mode 100644
index 0000000..2d10470
--- /dev/null
+++ b/packages/ui/src/components/alert.tsx
@@ -0,0 +1,79 @@
+import * as React from "react";
+import { cva, type VariantProps } from "class-variance-authority";
+
+import { cn } from "@minmon/ui/lib/utils";
+
+const alertVariants = cva(
+ "group/alert relative grid w-full gap-0.5 rounded-none border px-2.5 py-2 text-left text-xs has-data-[slot=alert-action]:relative has-data-[slot=alert-action]:pr-18 has-[>svg]:grid-cols-[auto_1fr] has-[>svg]:gap-x-2 *:[svg]:row-span-2 *:[svg]:translate-y-0 *:[svg]:text-current *:[svg:not([class*='size-'])]:size-4",
+ {
+ variants: {
+ variant: {
+ default: "bg-card text-card-foreground",
+ destructive:
+ "bg-card text-destructive *:data-[slot=alert-description]:text-destructive/90 *:[svg]:text-current",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ },
+ },
+);
+
+function Alert({
+ className,
+ variant,
+ ...props
+}: React.ComponentProps<"div"> & VariantProps) {
+ return (
+
+ );
+}
+
+function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+ svg]/alert:col-start-2 [&_a]:underline [&_a]:underline-offset-3 [&_a]:hover:text-foreground",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function AlertDescription({
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+
+ );
+}
+
+function AlertAction({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+
+ );
+}
+
+export { Alert, AlertTitle, AlertDescription, AlertAction };
diff --git a/packages/ui/src/components/button.tsx b/packages/ui/src/components/button.tsx
index 61e7223..0e6cc92 100644
--- a/packages/ui/src/components/button.tsx
+++ b/packages/ui/src/components/button.tsx
@@ -4,7 +4,7 @@ import { cva, type VariantProps } from "class-variance-authority";
import { Loader2Icon } from "lucide-react";
const buttonVariants = cva(
- "group/button relative inline-flex shrink-0 items-center justify-center rounded-none border border-transparent bg-clip-padding text-xs font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50 active:scale-[0.98] disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-1 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ "group/button relative inline-flex shrink-0 items-center justify-center rounded-none border border-transparent bg-clip-padding text-xs font-medium whitespace-nowrap transition-[color,background-color,border-color,box-shadow,transform,opacity] outline-none select-none focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50 active:scale-[0.96] disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-1 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
{
variants: {
variant: {
@@ -64,7 +64,7 @@ function Button({
aria-hidden="true"
className="absolute inset-0 inline-flex items-center justify-center"
>
-
+
) : null}
) {
+ return (
+ [data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function FieldLegend({
+ className,
+ variant = "legend",
+ ...props
+}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) {
+ return (
+
+ );
+}
+
+function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+
+ );
+}
+
+const fieldVariants = cva(
+ "group/field flex w-full gap-2 data-[invalid=true]:text-destructive",
+ {
+ variants: {
+ orientation: {
+ vertical: "flex-col *:w-full [&>.sr-only]:w-auto",
+ horizontal:
+ "flex-row items-center has-[>[data-slot=field-content]]:items-start *:data-[slot=field-label]:flex-auto has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
+ responsive:
+ "flex-col *:w-full @md/field-group:flex-row @md/field-group:items-center @md/field-group:*:w-auto @md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:*:data-[slot=field-label]:flex-auto [&>.sr-only]:w-auto @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
+ },
+ },
+ defaultVariants: {
+ orientation: "vertical",
+ },
+ },
+);
+
+function Field({
+ className,
+ orientation = "vertical",
+ ...props
+}: React.ComponentProps<"div"> & VariantProps) {
+ return (
+
+ );
+}
+
+function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+
+ );
+}
+
+function FieldLabel({
+ className,
+ ...props
+}: React.ComponentProps) {
+ return (
+ [data-slot=field]]:rounded-none has-[>[data-slot=field]]:border *:data-[slot=field]:p-2 dark:has-data-checked:border-primary/20 dark:has-data-checked:bg-primary/10",
+ "has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
+ return (
+
+ );
+}
+
+function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
+ return (
+ a]:underline [&>a]:underline-offset-4 [&>a:hover]:text-primary",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+function FieldSeparator({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"div"> & {
+ children?: React.ReactNode;
+}) {
+ return (
+
+
+ {children && (
+
+ {children}
+
+ )}
+
+ );
+}
+
+function FieldError({
+ className,
+ children,
+ errors,
+ ...props
+}: React.ComponentProps<"div"> & {
+ errors?: Array<{ message?: string } | undefined>;
+}) {
+ const content = useMemo(() => {
+ if (children) {
+ return children;
+ }
+
+ if (!errors?.length) {
+ return null;
+ }
+
+ const uniqueErrors = [
+ ...new Map(errors.map((error) => [error?.message, error])).values(),
+ ];
+
+ if (uniqueErrors?.length == 1) {
+ return uniqueErrors[0]?.message;
+ }
+
+ return (
+
+ {uniqueErrors.map(
+ (error, index) =>
+ error?.message && {error.message} ,
+ )}
+
+ );
+ }, [children, errors]);
+
+ if (!content) {
+ return null;
+ }
+
+ return (
+
+ {content}
+
+ );
+}
+
+export {
+ Field,
+ FieldLabel,
+ FieldDescription,
+ FieldError,
+ FieldGroup,
+ FieldLegend,
+ FieldSeparator,
+ FieldSet,
+ FieldContent,
+ FieldTitle,
+};
diff --git a/packages/ui/src/components/separator.tsx b/packages/ui/src/components/separator.tsx
new file mode 100644
index 0000000..843e554
--- /dev/null
+++ b/packages/ui/src/components/separator.tsx
@@ -0,0 +1,23 @@
+import { Separator as SeparatorPrimitive } from "@base-ui/react/separator";
+
+import { cn } from "@minmon/ui/lib/utils";
+
+function Separator({
+ className,
+ orientation = "horizontal",
+ ...props
+}: SeparatorPrimitive.Props) {
+ return (
+
+ );
+}
+
+export { Separator };
diff --git a/packages/ui/src/components/toggle-group.tsx b/packages/ui/src/components/toggle-group.tsx
new file mode 100644
index 0000000..07c3dc1
--- /dev/null
+++ b/packages/ui/src/components/toggle-group.tsx
@@ -0,0 +1,87 @@
+import * as React from "react";
+import { Toggle as TogglePrimitive } from "@base-ui/react/toggle";
+import { ToggleGroup as ToggleGroupPrimitive } from "@base-ui/react/toggle-group";
+import { type VariantProps } from "class-variance-authority";
+
+import { cn } from "@minmon/ui/lib/utils";
+import { toggleVariants } from "@minmon/ui/components/toggle";
+
+const ToggleGroupContext = React.createContext<
+ VariantProps & {
+ spacing?: number;
+ orientation?: "horizontal" | "vertical";
+ }
+>({
+ size: "default",
+ variant: "default",
+ spacing: 2,
+ orientation: "horizontal",
+});
+
+function ToggleGroup({
+ className,
+ variant,
+ size,
+ spacing = 2,
+ orientation = "horizontal",
+ children,
+ ...props
+}: ToggleGroupPrimitive.Props &
+ VariantProps & {
+ spacing?: number;
+ orientation?: "horizontal" | "vertical";
+ }) {
+ return (
+
+
+ {children}
+
+
+ );
+}
+
+function ToggleGroupItem({
+ className,
+ children,
+ variant = "default",
+ size = "default",
+ ...props
+}: TogglePrimitive.Props & VariantProps) {
+ const context = React.useContext(ToggleGroupContext);
+
+ return (
+
+ {children}
+
+ );
+}
+
+export { ToggleGroup, ToggleGroupItem };
diff --git a/packages/ui/src/components/toggle.tsx b/packages/ui/src/components/toggle.tsx
new file mode 100644
index 0000000..77bca03
--- /dev/null
+++ b/packages/ui/src/components/toggle.tsx
@@ -0,0 +1,43 @@
+import { Toggle as TogglePrimitive } from "@base-ui/react/toggle";
+import { cva, type VariantProps } from "class-variance-authority";
+
+import { cn } from "@minmon/ui/lib/utils";
+
+const toggleVariants = cva(
+ "group/toggle inline-flex items-center justify-center gap-1 rounded-none text-xs font-medium whitespace-nowrap transition-[color,background-color,border-color,box-shadow,transform,opacity] outline-none hover:bg-muted hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 active:scale-[0.96] disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 aria-pressed:bg-muted data-[state=on]:bg-muted dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
+ {
+ variants: {
+ variant: {
+ default: "bg-transparent",
+ outline: "border border-input bg-transparent hover:bg-muted",
+ },
+ size: {
+ default:
+ "h-8 min-w-8 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
+ sm: "h-7 min-w-7 rounded-none px-2.5 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5",
+ lg: "h-9 min-w-9 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ size: "default",
+ },
+ },
+);
+
+function Toggle({
+ className,
+ variant = "default",
+ size = "default",
+ ...props
+}: TogglePrimitive.Props & VariantProps) {
+ return (
+
+ );
+}
+
+export { Toggle, toggleVariants };
diff --git a/packages/ui/src/styles/globals.css b/packages/ui/src/styles/globals.css
index 95d4936..c48b00d 100644
--- a/packages/ui/src/styles/globals.css
+++ b/packages/ui/src/styles/globals.css
@@ -194,6 +194,6 @@
letter-spacing: var(--tracking-normal);
}
html {
- @apply font-sans;
+ @apply font-sans antialiased;
}
-}
\ No newline at end of file
+}