feat: initial auth rework

This commit is contained in:
Aarnav Tale
2026-03-07 17:10:34 -05:00
parent 6d70497758
commit 0f8e192b5c
39 changed files with 2110 additions and 1684 deletions
+45 -16
View File
@@ -1,20 +1,49 @@
import { eq } from 'drizzle-orm';
import { redirect } from 'react-router';
import { users } from '~/server/db/schema';
import type { Route } from './+types/onboarding-skip';
import { eq } from "drizzle-orm";
import { redirect } from "react-router";
import { users } from "~/server/db/schema";
import type { Route } from "./+types/onboarding-skip";
export async function loader({ request, context }: Route.LoaderArgs) {
try {
const { user } = await context.sessions.auth(request);
await context.db
.update(users)
.set({
onboarded: true,
})
.where(eq(users.sub, user.subject));
try {
const principal = await context.auth.require(request);
if (principal.kind !== "oidc") {
return redirect("/machines");
}
return redirect('/machines');
} catch {
return redirect('/login');
}
await context.db
.update(users)
.set({ onboarded: true })
.where(eq(users.sub, principal.user.subject));
return redirect("/machines");
} catch {
return redirect("/login");
}
}
export async function action({ request, context }: Route.ActionArgs) {
try {
const principal = await context.auth.require(request);
if (principal.kind !== "oidc") {
return redirect("/machines");
}
const formData = await request.formData();
const headscaleUserId = formData.get("headscale_user_id")?.toString();
if (headscaleUserId) {
await context.auth.linkHeadscaleUser(principal.user.id, headscaleUserId);
}
await context.db
.update(users)
.set({ onboarded: true })
.where(eq(users.sub, principal.user.subject));
return redirect("/machines");
} catch {
return redirect("/login");
}
}
+75 -30
View File
@@ -1,27 +1,29 @@
import { Icon } from "@iconify/react";
import { ArrowRight } from "lucide-react";
import { useEffect } from "react";
import { NavLink } from "react-router";
import { Form, NavLink } from "react-router";
import Button from "~/components/Button";
import Card from "~/components/Card";
import Link from "~/components/Link";
import Options from "~/components/Options";
import StatusCircle from "~/components/StatusCircle";
import { findHeadscaleUserBySubject } from "~/server/web/headscale-identity";
import { Machine } from "~/types";
import cn from "~/utils/cn";
import { useLiveData } from "~/utils/live-data";
import log from "~/utils/log";
import toast from "~/utils/toast";
import { getUserDisplayName } from "~/utils/user";
import type { Route } from "./+types/onboarding";
export async function loader({ request, context }: Route.LoaderArgs) {
const session = await context.sessions.auth(request);
const principal = await context.auth.require(request);
if (principal.kind !== "oidc") {
throw new Error("Onboarding is only available for OIDC users.");
}
// Try to determine the OS split between Linux, Windows, macOS, iOS, and Android
// We need to convert this to a known value to return it to the client so we can
// automatically tab to the correct download button.
const userAgent = request.headers.get("user-agent");
const os = userAgent?.match(/(Linux|Windows|Mac OS X|iPhone|iPad|Android)/);
let osValue = "linux";
@@ -47,45 +49,58 @@ export async function loader({ request, context }: Route.LoaderArgs) {
break;
}
const api = context.hsApi.getRuntimeClient(session.api_key);
const apiKey = context.auth.getHeadscaleApiKey(principal, context.oidc?.apiKey);
const api = context.hsApi.getRuntimeClient(apiKey);
const hsUserId = principal.user.headscaleUserId;
let firstMachine: Machine | undefined;
let needsUserLink = false;
let headscaleUsers: { id: string; name: string }[] = [];
try {
const nodes = await api.getNodes();
const node = nodes.find((n) => {
// Tag-only nodes have no user
if (!n.user || n.user.provider !== "oidc") {
return false;
const [nodes, apiUsers] = await Promise.all([api.getNodes(), api.getUsers()]);
if (hsUserId) {
firstMachine = nodes.find((n) => n.user?.id === hsUserId);
} else {
const matched = findHeadscaleUserBySubject(
apiUsers,
principal.user.subject,
principal.profile.email,
);
if (matched) {
await context.auth.linkHeadscaleUser(principal.user.id, matched.id);
firstMachine = nodes.find((n) => n.user?.id === matched.id);
} else {
needsUserLink = true;
headscaleUsers = apiUsers.map((u) => ({
id: u.id,
name: getUserDisplayName(u),
}));
}
// For some reason, headscale makes providerID a url where the
// last component is the subject, so we need to strip that out
const subject = n.user.providerId?.split("/").pop();
if (!subject) {
return false;
}
if (subject !== session.user.subject) {
return false;
}
return true;
});
firstMachine = node;
}
} catch (e) {
// If we cannot lookup nodes, we cannot proceed
log.debug("api", "Failed to lookup nodes %o", e);
}
return {
user: session.user,
user: {
subject: principal.user.subject,
name: principal.profile.name,
email: principal.profile.email,
username: principal.profile.username,
picture: principal.profile.picture,
},
osValue,
firstMachine,
needsUserLink,
headscaleUsers,
};
}
export default function Page({
loaderData: { user, osValue, firstMachine },
loaderData: { user, osValue, firstMachine, needsUserLink, headscaleUsers },
}: Route.ComponentProps) {
const { pause, resume } = useLiveData();
useEffect(() => {
@@ -107,6 +122,36 @@ export default function Page({
return (
<div className="fixed flex h-screen w-full items-center px-4">
<div className="mx-auto mb-24 grid w-fit grid-cols-1 gap-4 md:grid-cols-2">
{needsUserLink && headscaleUsers.length > 0 ? (
<Card className="col-span-2 mx-auto max-w-lg" variant="flat">
<Card.Title className="mb-4">Link your Headscale account</Card.Title>
<Card.Text className="mb-4">
Headplane couldn't automatically match your SSO identity to a Headscale user. Select
which Headscale user you are to continue.
</Card.Text>
<Form method="POST" action="/onboarding/skip">
<select
className={cn(
"w-full rounded-lg border p-2 mb-4",
"border-headplane-200 dark:border-headplane-700",
"bg-headplane-50 dark:bg-headplane-900",
)}
name="headscale_user_id"
required
>
<option value="">Select a user...</option>
{headscaleUsers.map((u) => (
<option key={u.id} value={u.id}>
{u.name}
</option>
))}
</select>
<Button className="w-full" type="submit" variant="heavy">
Link and Continue
</Button>
</Form>
</Card>
) : undefined}
<Card className="max-w-lg" variant="flat">
<Card.Title className="mb-8">
Welcome!
+13 -21
View File
@@ -1,13 +1,13 @@
import { createHash } from "node:crypto";
import { useEffect, useState } from "react";
import type { Machine, User } from "~/types";
import { getOidcSubject } from "~/server/web/headscale-identity";
import { Capabilities } from "~/server/web/roles";
import type { Machine, User } from "~/types";
import cn from "~/utils/cn";
import type { Route } from "./+types/overview";
import ManageBanner from "./components/manage-banner";
import UserRow from "./components/user-row";
import { userAction } from "./user-actions";
@@ -17,8 +17,8 @@ interface UserMachine extends User {
}
export async function loader({ request, context }: Route.LoaderArgs) {
const session = await context.sessions.auth(request);
const check = await context.sessions.check(request, Capabilities.read_users);
const principal = await context.auth.require(request);
const check = await context.auth.can(principal, Capabilities.read_users);
if (!check) {
// Not authorized to view this page
throw new Error(
@@ -26,9 +26,10 @@ export async function loader({ request, context }: Route.LoaderArgs) {
);
}
const writablePermission = await context.sessions.check(request, Capabilities.write_users);
const writablePermission = await context.auth.can(principal, Capabilities.write_users);
const api = context.hsApi.getRuntimeClient(session.api_key);
const apiKey = context.auth.getHeadscaleApiKey(principal, context.oidc?.apiKey);
const api = context.hsApi.getRuntimeClient(apiKey);
const [nodes, apiUsers] = await Promise.all([api.getNodes(), api.getUsers()]);
const users = apiUsers.map((user) => ({
@@ -56,22 +57,13 @@ export async function loader({ request, context }: Route.LoaderArgs) {
return "no-oidc";
}
if (user.provider === "oidc" && user.providerId) {
// For some reason, headscale makes providerID a url where the
// last component is the subject, so we need to strip that out
const subject = user.providerId.split("/").pop();
if (!subject) {
return "invalid-oidc";
}
const role = await context.sessions.roleForSubject(subject);
return role ?? "no-role";
const subject = getOidcSubject(user);
if (!subject) {
return "invalid-oidc";
}
// No role means the user is not registered in Headplane, but they
// are in Headscale. We also need to handle what happens if someone
// logs into the UI and they don't have a Headscale setup.
return "no-role";
const role = await context.auth.roleForSubject(subject);
return role ?? "no-role";
}),
);
+96 -99
View File
@@ -1,115 +1,112 @@
import { data } from 'react-router';
import { Capabilities, Roles } from '~/server/web/roles';
import type { Route } from './+types/overview';
import { data } from "react-router";
import { getOidcSubject } from "~/server/web/headscale-identity";
import { Capabilities } from "~/server/web/roles";
import type { Role } from "~/server/web/roles";
import type { Route } from "./+types/overview";
export async function userAction({ request, context }: Route.ActionArgs) {
const session = await context.sessions.auth(request);
const check = await context.sessions.check(request, Capabilities.write_users);
if (!check) {
throw data('You do not have permission to update users', {
status: 403,
});
}
const principal = await context.auth.require(request);
const check = await context.auth.can(principal, Capabilities.write_users);
if (!check) {
throw data("You do not have permission to update users", {
status: 403,
});
}
const formData = await request.formData();
const action = formData.get('action_id')?.toString();
if (!action) {
throw data('Missing `action_id` in the form data.', {
status: 404,
});
}
const formData = await request.formData();
const action = formData.get("action_id")?.toString();
if (!action) {
throw data("Missing `action_id` in the form data.", {
status: 404,
});
}
const api = context.hsApi.getRuntimeClient(session.api_key);
switch (action) {
case 'create_user': {
const name = formData.get('username')?.toString();
const displayName = formData.get('display_name')?.toString();
const email = formData.get('email')?.toString();
const apiKey = context.auth.getHeadscaleApiKey(principal, context.oidc?.apiKey);
const api = context.hsApi.getRuntimeClient(apiKey);
switch (action) {
case "create_user": {
const name = formData.get("username")?.toString();
const displayName = formData.get("display_name")?.toString();
const email = formData.get("email")?.toString();
if (!name) {
throw data('Missing `username` in the form data.', {
status: 400,
});
}
if (!name) {
throw data("Missing `username` in the form data.", {
status: 400,
});
}
await api.createUser(name, email, displayName);
return { message: 'User created successfully' };
}
case 'delete_user': {
const userId = formData.get('user_id')?.toString();
if (!userId) {
throw data('Missing `user_id` in the form data.', {
status: 400,
});
}
await api.createUser(name, email, displayName);
return { message: "User created successfully" };
}
case "delete_user": {
const userId = formData.get("user_id")?.toString();
if (!userId) {
throw data("Missing `user_id` in the form data.", {
status: 400,
});
}
await api.deleteUser(userId);
return { message: 'User deleted successfully' };
}
case 'rename_user': {
const userId = formData.get('user_id')?.toString();
const newName = formData.get('new_name')?.toString();
if (!userId || !newName) {
return data({ success: false }, 400);
}
await api.deleteUser(userId);
return { message: "User deleted successfully" };
}
case "rename_user": {
const userId = formData.get("user_id")?.toString();
const newName = formData.get("new_name")?.toString();
if (!userId || !newName) {
return data({ success: false }, 400);
}
const users = await api.getUsers(userId);
const user = users.find((user) => user.id === userId);
if (!user) {
throw data(`No user found with id: ${userId}`, { status: 400 });
}
const users = await api.getUsers(userId);
const user = users.find((user) => user.id === userId);
if (!user) {
throw data(`No user found with id: ${userId}`, { status: 400 });
}
if (user.provider === 'oidc') {
// OIDC users cannot be renamed via this endpoint, return an error
throw data('Users managed by OIDC cannot be renamed', {
status: 403,
});
}
if (user.provider === "oidc") {
// OIDC users cannot be renamed via this endpoint, return an error
throw data("Users managed by OIDC cannot be renamed", {
status: 403,
});
}
await api.renameUser(userId, newName);
return { message: 'User renamed successfully' };
}
case 'reassign_user': {
const userId = formData.get('user_id')?.toString();
const newRole = formData.get('new_role')?.toString();
if (!userId || !newRole) {
throw data('Missing `user_id` or `new_role` in the form data.', {
status: 400,
});
}
await api.renameUser(userId, newName);
return { message: "User renamed successfully" };
}
case "reassign_user": {
const userId = formData.get("user_id")?.toString();
const newRole = formData.get("new_role")?.toString();
if (!userId || !newRole) {
throw data("Missing `user_id` or `new_role` in the form data.", {
status: 400,
});
}
const users = await api.getUsers(userId);
const user = users.find((user) => user.id === userId);
if (!user?.providerId) {
throw data('Specified user is not an OIDC user', {
status: 400,
});
}
const users = await api.getUsers(userId);
const user = users.find((user) => user.id === userId);
if (!user) {
throw data("Specified user not found", {
status: 400,
});
}
// For some reason, headscale makes providerID a url where the
// last component is the subject, so we need to strip that out
const subject = user.providerId?.split('/').pop();
if (!subject) {
throw data(
'Malformed `providerId` for the specified user. Cannot find subject.',
{ status: 400 },
);
}
const subject = getOidcSubject(user);
if (!subject) {
throw data("Specified user is not an OIDC user or has no subject.", { status: 400 });
}
const result = await context.sessions.reassignSubject(
subject,
newRole as keyof typeof Roles,
);
const result = await context.auth.reassignSubject(subject, newRole as Role);
if (!result) {
throw data('Failed to reassign user role.', { status: 500 });
}
if (!result) {
throw data("Failed to reassign user role.", { status: 500 });
}
return { message: 'User reassigned successfully' };
}
default:
throw data('Invalid `action_id` provided.', {
status: 400,
});
}
return { message: "User reassigned successfully" };
}
default:
throw data("Invalid `action_id` provided.", {
status: 400,
});
}
}