feat(auth): add Owner authentication source settings

Manage Yggdrasil providers from the panel using durable platform settings, protected identity namespaces and atomic revisions. Apply changes to subsequent logins and profile lookups without restarting. Return operator-host logouts to the login method selection page.
This commit is contained in:
Lemon-miaow committed 2026-10-04 22:18:37 +08:00
1 parent 2c98e8b2ab
commit 61b283ae2f
33 files changed
+1466 -18

No files matched your search

+40
View File
@@ -3,6 +3,8 @@ import type { IncomingMessage, ServerResponse } from "node:http";
import { gzipSync } from "node:zlib";
import type { Plugin } from "vite";
import type {
AuthSourceConfig,
AuthSourcesSettings,
AutostartPolicy,
BackupView,
Build,
@@ -89,6 +91,7 @@ interface MockState {
passkeys: Record<AccountID, { id: string; name: string; created_at: string }[]>;
submissions: Submission[];
updateWindow: { start: string | null; end: string | null };
authSources: AuthSourcesSettings;
// Each server's world volume, seeded on first visit.
files: Record<string, MockTree>;
}
@@ -452,6 +455,11 @@ function initialState(): MockState {
},
],
updateWindow: { start: null, end: null },
authSources: {
sources: [{ tag: "littleskin", prefix: "LS", url: "https://littleskin.cn/api/yggdrasil/sessionserver/session/minecraft/hasJoined", api_url: "", enabled: true }],
revision: "installation-defaults",
managed: false,
},
files: {},
};
}
@@ -1008,6 +1016,38 @@ async function handlePublic(ctx: RequestContext): Promise<boolean> {
async function handleSession(ctx: SessionContext): Promise<boolean> {
switch (route(ctx)) {
case "GET settings/auth-sources":
case "PUT settings/auth-sources":
case "POST settings/auth-sources/test": {
if (!isOwner(ctx.account.role)) {
sendError(ctx.res, 403, "forbidden", "Owner account required");
return true;
}
if (is("GET", ctx)) {
sendJSON(ctx.res, 200, ctx.state.authSources);
} else if (is("PUT", ctx)) {
const body = await readJSON<{ sources: AuthSourceConfig[]; revision: string }>(ctx.req);
if (body.revision !== ctx.state.authSources.revision) {
sendError(ctx.res, 409, "auth_sources_changed", "authentication sources changed; reload before saving");
} else if (ctx.state.authSources.sources.some((source) => !body.sources.some((s) => s.tag === source.tag))) {
sendError(ctx.res, 409, "auth_source_tag_locked", "disable saved sources instead of removing or renaming them");
} else {
ctx.state.authSources = { sources: body.sources, revision: createHash("sha256").update(JSON.stringify(body.sources)).digest("hex"), managed: true };
sendJSON(ctx.res, 200, ctx.state.authSources);
}
} else {
await readJSON<AuthSourceConfig>(ctx.req);
sendJSON(ctx.res, 200, { ok: true, status: 204, elapsed_ms: 20 });
}
return true;
}
case "GET account/link/sources":
if (!isAdmin(ctx.account.role)) {
sendError(ctx.res, 403, "forbidden", "admin account required");
return true;
}
sendJSON(ctx.res, 200, { sources: [{ tag: "mojang", prefix: "", lookup_available: true }, ...ctx.state.authSources.sources.filter((source) => source.enabled).map((source) => ({ tag: source.tag, prefix: source.prefix, lookup_available: !!source.api_url || source.url.endsWith("/sessionserver/session/minecraft/hasJoined") }))] });
return true;
case "GET platform/db-backup": {
if (!isAdmin(ctx.account.role)) {
sendError(ctx.res, 403, "forbidden", "admin account required");
+84
View File
@@ -0,0 +1,84 @@
import { test, expect, t, expectFitsScreen } from "./fixtures";
test("Owner manages durable authentication sources from the sidebar", async ({ page, signIn }) => {
await signIn("owner");
await page.goto("/");
await page.getByRole("link", { name: t("navigation:auth_sources"), exact: true }).click();
await expect(page).toHaveURL(/\/admin\/auth-sources$/);
await expect(page.getByLabel(t("authSources:tag"))).toHaveValue("littleskin");
await expect(page.getByLabel(t("authSources:tag"))).toHaveAttribute("readonly", "");
await page.getByRole("button", { name: t("authSources:add"), exact: true }).click();
await page.getByLabel(t("authSources:tag")).nth(1).fill("custom");
await page.getByLabel(t("authSources:prefix")).nth(1).fill("CS");
await page.getByLabel(t("authSources:url"), { exact: true }).nth(1).fill("https://custom.example/sessionserver/session/minecraft/hasJoined");
await page.getByRole("button", { name: t("authSources:test"), exact: true }).nth(1).click();
await expect(page.getByText(t("authSources:test_ok", { ms: 20 }), { exact: true })).toBeVisible();
await page.getByRole("button", { name: t("authSources:move_up"), exact: true }).nth(1).click();
await page.getByRole("checkbox", { name: t("authSources:enabled"), exact: true }).nth(1).uncheck();
await page.getByRole("button", { name: t("authSources:save"), exact: true }).click();
await expect(page.getByText(t("authSources:saved"), { exact: true })).toBeVisible();
await page.reload();
await expect(page.getByLabel(t("authSources:tag")).nth(0)).toHaveValue("custom");
await expect(page.getByRole("checkbox", { name: t("authSources:enabled"), exact: true }).nth(1)).not.toBeChecked();
await expect(page.getByRole("button", { name: t("authSources:remove"), exact: true })).toHaveCount(0);
const available = await page.request.get("/api/v1/account/link/sources");
expect((await available.json()).sources.map((source: { tag: string }) => source.tag)).toEqual(["mojang", "custom"]);
await expectFitsScreen(page);
await page.screenshot({ path: "/tmp/felis-auth-sources.png", fullPage: true });
});
test("source fields stay visible while initial configuration is loading", async ({ page, signIn }) => {
await signIn("owner");
let release!: () => void;
const pending = new Promise<void>((resolve) => { release = resolve; });
await page.route("**/api/v1/settings/auth-sources", async (route) => { await pending; await route.continue(); });
await page.goto("/admin/auth-sources");
await expect(page.getByLabel(t("authSources:tag"))).toBeVisible();
await expect(page.getByLabel(t("authSources:tag"))).toBeDisabled();
await expect(page.getByText(t("authSources:loading"), { exact: true }).first()).toBeVisible();
release();
await expect(page.getByLabel(t("authSources:tag"))).toBeEnabled();
});
test("a player has neither an authentication source entry nor access to its API", async ({ page, signIn }) => {
await signIn("linked");
await page.goto("/admin/auth-sources");
await expect(page.getByText(t("common:not_authorized_title"))).toBeVisible();
await expect(page.getByRole("link", { name: t("navigation:auth_sources"), exact: true })).toHaveCount(0);
const response = await page.request.get("/api/v1/settings/auth-sources");
expect(response.status()).toBe(403);
});
for (const path of ["/servers", "/account"]) {
test(`logout from ${path} on the operator host returns to login methods`, async ({ page, signIn }) => {
await page.route("**/config.json", async (route) => {
const response = await route.fetch();
await route.fulfill({ response, json: { ...await response.json(), adminHostname: "localhost" } });
});
await signIn("owner");
await page.goto(path);
const logout = page.getByRole("button", { name: t("account:sign_out"), exact: true });
await (path === "/account" ? logout.last() : logout.first()).click();
await expect(page).toHaveURL(/\/login\?/);
await expect(page.getByRole("button", { name: t("auth:passkey_btn"), exact: true })).toBeVisible();
await expect(page.getByRole("button", { name: t("auth:tab_op_btn"), exact: true })).toBeVisible();
await expect(page.getByRole("button", { name: t("auth:op_start_btn"), exact: true })).toHaveCount(0);
await page.getByRole("button", { name: t("auth:tab_op_btn"), exact: true }).click();
await expect(page.getByRole("button", { name: t("auth:op_start_btn"), exact: true })).toBeVisible();
});
}
test("Chinese authentication settings render in both themes", async ({ page, signIn }) => {
await page.setViewportSize({ width: 1440, height: 1000 });
await page.addInitScript(() => localStorage.setItem("felis-lang", "zh-CN"));
await signIn("owner");
await page.emulateMedia({ colorScheme: "dark" });
await page.goto("/admin/auth-sources");
await expect(page.getByRole("heading", { name: "认证源", exact: true })).toBeVisible();
await expect(page.getByLabel("永久标识")).toHaveValue("littleskin");
await expectFitsScreen(page);
await page.screenshot({ path: "/tmp/felis-auth-sources-zh-dark.png", fullPage: true });
await page.getByRole("button", { name: "切换主题", exact: true }).click();
await expectFitsScreen(page);
await page.screenshot({ path: "/tmp/felis-auth-sources-zh-light.png", fullPage: true });
});
+10
View File
@@ -20,6 +20,7 @@ for (const [account, path] of [
["linked", "/account"],
["owner", "/servers"],
["owner", "/admin/users"],
["owner", "/admin/auth-sources"],
["owner", "/servers/survival/luckperms"],
] as const) {
test(`${path} fits a 375px screen for ${account}`, async ({ page, signIn }) => {
@@ -61,3 +62,12 @@ test("login customization fits a phone and retains a saved title", async ({ page
await page.reload();
await expect(page.getByLabel(t("lobby:bookTitle"))).toHaveValue("Our Network");
});
test("authentication source drafts with long IDs fit a phone", async ({ page, signIn }) => {
await signIn("owner");
await page.goto("/admin/auth-sources");
await page.getByRole("button", { name: t("authSources:add"), exact: true }).click();
await page.getByLabel(t("authSources:tag")).nth(1).fill("a".repeat(128));
await expectFitsScreen(page);
await expect(page.getByRole("button", { name: t("authSources:remove"), exact: true })).toBeVisible();
});
+3 -1
View File
@@ -65,6 +65,7 @@ const LobbyPage = lazyWithReload(() =>
const UpdatesPage = lazyWithReload(() =>
import("@/pages/admin/UpdatesPage").then((m) => ({ default: m.UpdatesPage })),
);
const AuthSourcesPage = lazyWithReload(() => import("@/pages/admin/AuthSourcesPage").then((m) => ({ default: m.AuthSourcesPage })));
// Three UX surfaces over two Zero-Trust tiers (DESIGN-WEB-3SIDES):
// / User-Side — app-tier, every authenticated principal
@@ -129,8 +130,9 @@ export default function App() {
<Route path="builds" element={<ImageBuildPage />} />
<Route path="submissions" element={<SubmissionsPage />} />
<Route path="updates" element={<UpdatesPage />} />
{/* Owner-gated: user management (one level above admin). */}
{/* Owner-gated platform settings and user management. */}
<Route element={<RequireOwner />}>
<Route path="auth-sources" element={<AuthSourcesPage />} />
<Route path="users" element={<UsersPage />} />
<Route path="users/:id" element={<ValidParam param="id" pattern={USER_ID_PARAM} />}>
<Route index element={<UserDetailPage />} />
+4
View File
@@ -13,6 +13,8 @@ import enNavigation from "./resources/en-US/navigation.json";
import enBackups from "./resources/en-US/backups.json";
import enSubmissions from "./resources/en-US/submissions.json";
import enFiles from "./resources/en-US/files.json";
import enAuthSources from "./resources/en-US/authSources.json";
import zhAuthSources from "./resources/zh-CN/authSources.json";
import enLobby from "./resources/en-US/lobby.json";
import zhLobby from "./resources/zh-CN/lobby.json";
import enSchedules from "./resources/en-US/schedules.json";
@@ -49,6 +51,7 @@ export const i18nOptions: InitOptions = {
files: enFiles,
schedules: enSchedules,
lobby: enLobby,
authSources: enAuthSources,
},
"zh-CN": {
common: zhCommon,
@@ -65,6 +68,7 @@ export const i18nOptions: InitOptions = {
files: zhFiles,
schedules: zhSchedules,
lobby: zhLobby,
authSources: zhAuthSources,
},
},
supportedLngs: [...SUPPORTED_LANGUAGES],
@@ -0,0 +1,40 @@
{
"title": "Authentication sources",
"subtitle": "Manage Minecraft identity providers and their verification priority.",
"builtin_title": "Mojang · built in, checked first",
"builtin_hint": "Official accounts keep their original UUIDs. This source is always enabled and cannot be replaced or reordered.",
"custom_title": "Third-party sources",
"priority_hint": "Enabled sources are checked from top to bottom after Mojang.",
"reload": "Reload",
"add": "Add source",
"new_source": "New source",
"loading": "Loading authentication sources…",
"enabled": "Enabled",
"move_up": "Move source up",
"move_down": "Move source down",
"remove": "Remove unsaved source",
"tag": "Permanent source ID",
"tag_hint": "A unique ID without colons or surrounding spaces. It becomes permanent when saved.",
"tag_locked": "This ID is fixed to preserve player UUIDs and account links.",
"prefix": "Name collision prefix",
"prefix_hint": "1–4 letters or digits, used when a player has an official account’s name.",
"url": "Authentication endpoint (hasJoined)",
"url_hint": "Use HTTPS. HTTP is allowed only for localhost or private IPs. Do not include a query or fragment.",
"api_url": "Role lookup API root (optional)",
"api_hint": "Leave empty for a standard hasJoined URL; otherwise provide the Yggdrasil API root for role lookup.",
"test": "Test connection",
"testing": "Testing…",
"test_hint": "Checks whether the login endpoint rejects an unused session correctly.",
"test_ok": "Authentication endpoint passed ({{ms}} ms).",
"test_status": "Endpoint returned HTTP {{status}}; expected 204 for an unused session.",
"empty": "Only official accounts are enabled. Add a source to accept another provider.",
"disable_hint": "Disable a saved source to stop accepting its logins. Its ID stays reserved so identities can be restored later. Launchers must use the same provider.",
"invalid": "Check source IDs, unique prefixes and complete HTTP(S) addresses without queries or fragments.",
"unsaved": "Unsaved changes · saving applies to the next login and role lookup",
"active": "Saved sources are active; no restart is required.",
"defaults": "Using installation defaults. Saved panel configuration takes precedence.",
"discard": "Discard changes",
"save": "Save & apply",
"saving": "Saving…",
"saved": "Saved and active. New logins and role lookups use this configuration; online players stay connected."
}
+4 -1
View File
@@ -141,5 +141,8 @@
"auth_source_unknown": "Select a configured authentication source.",
"auth_source_unavailable": "The authentication source is unavailable or returned an invalid role. Try again later.",
"auth_source_lookup_unsupported": "Role lookup is not configured for this authentication source.",
"minecraft_profile_not_found": "No role matched in this source. Check the role name or UUID."
"minecraft_profile_not_found": "No role matched in this source. Check the role name or UUID.",
"auth_sources_unavailable": "Authentication source management is unavailable.",
"auth_sources_changed": "Authentication sources changed. Discard your edits and reload before saving.",
"auth_source_tag_locked": "Saved source IDs cannot be renamed or removed. Disable the source instead."
}
@@ -10,5 +10,6 @@
"admin_builds": "Build Pipeline",
"admin_submissions": "Submissions",
"admin_updates": "Maintenance & Backups",
"admin_lobby": "Login & lobby"
"admin_lobby": "Login & lobby",
"auth_sources": "Authentication sources"
}
@@ -0,0 +1,40 @@
{
"title": "认证源",
"subtitle": "管理 Minecraft 身份认证服务及验证顺序。",
"builtin_title": "Mojang · 内置,优先验证",
"builtin_hint": "正版账号保留原有 UUID。此认证源始终启用,不能替换或调整顺序。",
"custom_title": "第三方认证源",
"priority_hint": "正版验证之后,按下方顺序查询已启用的认证源。",
"reload": "重新读取",
"add": "添加认证源",
"new_source": "新认证源",
"loading": "正在加载认证源…",
"enabled": "启用",
"move_up": "上移认证源",
"move_down": "下移认证源",
"remove": "移除未保存的认证源",
"tag": "永久标识",
"tag_hint": "标识须唯一,不能包含冒号或首尾空格。保存后将固定。",
"tag_locked": "此标识已固定,用于保留玩家 UUID 和账号绑定。",
"prefix": "重名处理前缀",
"prefix_hint": "1–4 位字母或数字。第三方角色与正版角色重名时使用。",
"url": "认证接口(hasJoined)",
"url_hint": "使用 HTTPS;仅本机或私有 IP 允许 HTTP。地址不能带查询参数或片段。",
"api_url": "角色查询 API 根地址(选填)",
"api_hint": "标准 hasJoined 地址可留空;使用自定义认证路径时,填写 Yggdrasil API 根地址,以便按角色名或 UUID 查询。",
"test": "测试连接",
"testing": "正在测试…",
"test_hint": "检查认证接口能否正确拒绝一个未登录的会话。",
"test_ok": "认证接口检查通过({{ms}} 毫秒)。",
"test_status": "接口返回 HTTP {{status}};未登录会话应返回 204,检查未通过。",
"empty": "当前仅接受正版 Minecraft 账号。添加认证源后可接入其他认证服务。",
"disable_hint": "停用已保存的认证源后,将不再接受该源的登录;标识仍保留,方便之后恢复玩家身份。玩家启动器也须配置同一个认证站。",
"invalid": "请检查永久标识、不能重复的重名前缀,以及不含查询参数或片段的完整 HTTP(S) 地址。",
"unsaved": "有未保存更改 · 保存后用于下一次登录和角色查询",
"active": "已保存的认证源正在生效,无需重启。",
"defaults": "当前使用安装配置。保存后将持久保存在面板中,并优先于安装配置。",
"discard": "放弃更改",
"save": "保存并生效",
"saving": "正在保存…",
"saved": "已保存并生效。下一次登录和角色查询使用新配置;在线玩家不会断开。"
}
+4 -1
View File
@@ -141,5 +141,8 @@
"auth_source_unknown": "请选择已配置的认证源。",
"auth_source_unavailable": "认证源暂时不可用或返回了无效角色,请稍后重试。",
"auth_source_lookup_unsupported": "此认证源尚未配置角色查询地址。",
"minecraft_profile_not_found": "在所选认证源中没有找到这个角色,请检查角色名或 UUID。"
"minecraft_profile_not_found": "在所选认证源中没有找到这个角色,请检查角色名或 UUID。",
"auth_sources_unavailable": "认证源管理暂不可用。",
"auth_sources_changed": "认证源已被其他操作修改。请放弃当前更改并重新读取后再保存。",
"auth_source_tag_locked": "已保存的认证源标识不能改名或移除,请使用停用。"
}
@@ -10,5 +10,6 @@
"admin_builds": "构建流水线",
"admin_submissions": "审核提交",
"admin_updates": "维护与备份",
"admin_lobby": "登录与大厅"
"admin_lobby": "登录与大厅",
"auth_sources": "认证源"
}
+6
View File
@@ -21,6 +21,8 @@ import type {
KickResult,
LinkResult,
MinecraftAuthSource,
AuthSourceConfig,
AuthSourcesSettings,
MinecraftProfile,
LinkStatus,
BindResult,
@@ -950,6 +952,10 @@ export const api = rejectingSync({
linkSources: () => request<{ sources: MinecraftAuthSource[] }>("GET", "/account/link/sources"),
getAuthSources: () => request<AuthSourcesSettings>("GET", "/settings/auth-sources"),
setAuthSources: (sources: AuthSourceConfig[], revision: string) => request<AuthSourcesSettings>("PUT", "/settings/auth-sources", { sources, revision }),
testAuthSource: (source: AuthSourceConfig) => request<{ ok: boolean; status: number; elapsed_ms: number }>("POST", "/settings/auth-sources/test", source),
lookupProfile: (source: string, profile: string) =>
request<MinecraftProfile>("GET", `/account/link/profile?${new URLSearchParams({ source, profile })}`),
+2
View File
@@ -9,6 +9,7 @@ import {
ClipboardCheck,
Upload,
Clock,
ShieldCheck,
type LucideIcon,
} from "lucide-react";
@@ -76,6 +77,7 @@ export const NAV_SECTIONS: NavSection[] = [
ownerOnly: true,
items: [
{ to: "/admin/users", key: "admin_users", icon: Users },
{ to: "/admin/auth-sources", key: "auth_sources", icon: ShieldCheck },
],
},
];
+156
View File
@@ -1243,6 +1243,47 @@ export interface paths {
patch?: never;
trace?: never;
};
"/api/v1/settings/auth-sources": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/** Read authentication sources (Owner). */
get: operations["getAuthSources"];
/**
* Save authentication sources (Owner, fresh reauthentication).
* @description Atomically persists an override in platform_settings. It applies to the next login and role lookup on every API replica without restarting; existing players stay online. Tags identify permanent UUID namespaces; retain every saved tag and disable unwanted sources. Mojang remains built-in and trusted, while configured sources always remain third-party. Nano remains TOML-only.
*/
put: operations["setAuthSources"];
post?: never;
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/settings/auth-sources/test": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
/**
* Probe a hasJoined endpoint (Owner).
* @description Checks an unsaved source with a fresh random serverId. A healthy endpoint returns 204 for a session that never joined. Uses a five-second timeout, verified TLS and no redirects. This tests connectivity and hasJoined behavior, not launcher login or profile lookup. Does not save configuration.
*/
post: operations["testAuthSource"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/api/v1/updates/window": {
parameters: {
query?: never;
@@ -2863,6 +2904,25 @@ export interface paths {
export type webhooks = Record<string, never>;
export interface components {
schemas: {
AuthSourceConfig: {
/** @description Permanent UUID namespace; saved tags cannot be renamed or removed. mojang is reserved. */
tag: string;
/** @description Unique case-insensitive display prefix. */
prefix: string;
/** @description hasJoined endpoint; HTTPS required except for localhost or private literal IP addresses. No query or fragment. */
url: string;
/** @description Optional Yggdrasil API base for role lookup; empty infers it from the standard hasJoined suffix. */
api_url: string;
enabled: boolean;
};
AuthSourcesSettings: {
/** @description Third-party sources in priority order; built-in Mojang always precedes them and is immutable. */
sources: components["schemas"]["AuthSourceConfig"][];
/** @description Opaque revision to send unchanged when saving; stale or concurrent writes return 409. */
revision: string;
/** @description True when stored in platform_settings; false while using installation TOML defaults. */
managed: boolean;
};
/** @description Uniform error envelope emitted by every handler (internal/api/errors.go). */
Error: {
error: {
@@ -6669,6 +6729,102 @@ export interface operations {
401: components["responses"]["Unauthorized"];
};
};
getAuthSources: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Current third-party sources and their revision. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["AuthSourcesSettings"];
};
};
401: components["responses"]["Unauthorized"];
403: components["responses"]["Forbidden"];
503: components["responses"]["ServiceUnavailable"];
};
};
setAuthSources: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
"application/json": {
sources: components["schemas"]["AuthSourceConfig"][];
revision: string;
};
};
};
responses: {
/** @description Saved configuration and new revision. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["AuthSourcesSettings"];
};
};
400: components["responses"]["BadRequest"];
401: components["responses"]["Unauthorized"];
403: components["responses"]["Forbidden"];
/** @description auth_sources_changed or auth_source_tag_locked; reload instead of overwriting another Owner's changes. */
409: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["Error"];
};
};
503: components["responses"]["ServiceUnavailable"];
};
};
testAuthSource: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
"application/json": components["schemas"]["AuthSourceConfig"];
};
};
responses: {
/** @description Probe result; non-204 status has ok=false. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": {
ok: boolean;
status: number;
/** Format: int64 */
elapsed_ms: number;
};
};
};
400: components["responses"]["BadRequest"];
401: components["responses"]["Unauthorized"];
403: components["responses"]["Forbidden"];
503: components["responses"]["ServiceUnavailable"];
};
};
getUpdateWindow: {
parameters: {
query?: never;
+14
View File
@@ -362,6 +362,20 @@ export interface MinecraftAuthSource {
lookup_available: boolean;
}
export interface AuthSourceConfig {
tag: string;
prefix: string;
url: string;
api_url: string;
enabled: boolean;
}
export interface AuthSourcesSettings {
sources: AuthSourceConfig[];
revision: string;
managed: boolean;
}
export interface MinecraftProfile {
source: string;
name: string;
+8
View File
@@ -71,6 +71,14 @@ beforeEach(() => {
});
describe("Login", () => {
it("starts with login methods on the operator host after signing out", async () => {
config.value.adminHostname = window.location.hostname;
await renderLogin();
expect(screen.getByRole("button", { name: t("auth:passkey_btn") })).toBeTruthy();
expect(screen.getByRole("button", { name: t("auth:tab_op_btn") })).toBeTruthy();
expect(screen.queryByRole("button", { name: t("auth:op_start_btn") })).toBeNull();
});
it("reads out why the code could not be sent", async () => {
calls.authEmailStart.mockRejectedValue({ status: 429, code: "otp_resend_cooldown", message: "" });
await renderLogin();
+2 -3
View File
@@ -68,14 +68,13 @@ export function Login() {
return () => clearTimeout(timer);
}, [countdown]);
// Tier-aware copy: on the op.console hostname the staff door is the default tab
// (the player doors refuse staff accounts anyway).
// The operator hostname changes the copy, while every visit starts with the
// login methods (including passkeys). Staff explicitly choose vouched login.
useEffect(() => {
void loadConfig().then((cfg) => {
setJoinAddr(entryAddress(cfg));
if (cfg.adminHostname && window.location.hostname === cfg.adminHostname) {
setIsOpHost(true);
setActiveTab("op");
}
});
}, []);
@@ -0,0 +1,114 @@
// @vitest-environment jsdom
import { beforeEach, describe, expect, it, vi } from "vitest";
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MemoryRouter } from "react-router-dom";
import { AuthSourcesPage } from "./AuthSourcesPage";
import type { AuthSourceConfig, AuthSourcesSettings } from "@/lib/types";
const calls = vi.hoisted(() => ({ getAuthSources: vi.fn(), setAuthSources: vi.fn(), testAuthSource: vi.fn() }));
vi.mock("@/lib/api", async (original) => ({ ...await original<typeof import("@/lib/api")>(), api: calls }));
const source = (tag = "littleskin", prefix = "LS"): AuthSourceConfig => ({ tag, prefix, url: "https://example.org/sessionserver/session/minecraft/hasJoined", api_url: "", enabled: true });
const settings = (sources = [source()]): AuthSourcesSettings => ({ sources, revision: "original", managed: false });
function page() { render(<MemoryRouter><AuthSourcesPage /></MemoryRouter>); }
const button = (name: string) => screen.getByRole("button", { name });
const field = (label: string, index = 0) => screen.getAllByLabelText(label)[index] as HTMLInputElement;
async function ready() { await waitFor(() => expect(field("Permanent source ID").disabled).toBe(false)); }
beforeEach(() => {
vi.clearAllMocks();
calls.getAuthSources.mockResolvedValue(settings());
calls.setAuthSources.mockImplementation(async (sources) => ({ sources, revision: "saved", managed: true }));
calls.testAuthSource.mockResolvedValue({ ok: true, status: 204, elapsed_ms: 18 });
});
describe("AuthSourcesPage", () => {
it("shows disabled fields while loading, then protects saved IDs", async () => {
let resolve!: (settings: AuthSourcesSettings) => void;
calls.getAuthSources.mockReturnValue(new Promise((r) => { resolve = r; }));
page();
expect(field("Permanent source ID").disabled).toBe(true);
expect(field("Authentication endpoint (hasJoined)").value).toBe("");
expect((button("Save & apply") as HTMLButtonElement).disabled).toBe(true);
expect(screen.getByRole("status").textContent).toContain("Loading authentication sources");
await act(async () => resolve(settings()));
await ready();
expect(field("Permanent source ID").readOnly).toBe(true);
expect(screen.queryByRole("button", { name: "Remove unsaved source" })).toBeNull();
});
it("adds a source, fixes a duplicate ID, saves and locks it without sending UI state", async () => {
page(); await ready();
await userEvent.click(button("Add source"));
fireEvent.change(field("Permanent source ID", 1), { target: { value: "littleskin" } });
expect(field("Permanent source ID", 1).readOnly).toBe(false);
expect(button("Remove unsaved source")).toBeTruthy();
fireEvent.change(field("Permanent source ID", 1), { target: { value: "custom" } });
fireEvent.change(field("Name collision prefix", 1), { target: { value: "CS" } });
fireEvent.change(field("Authentication endpoint (hasJoined)", 1), { target: { value: "https://custom.example/check" } });
fireEvent.change(field("Role lookup API root (optional)", 1), { target: { value: "https://custom.example" } });
await userEvent.click(button("Save & apply"));
await screen.findByText("Saved and active. New logins and role lookups use this configuration; online players stay connected.");
expect(calls.setAuthSources).toHaveBeenCalledWith([source(), { tag: "custom", prefix: "CS", url: "https://custom.example/check", api_url: "https://custom.example", enabled: true }], "original");
expect(field("Permanent source ID", 1).readOnly).toBe(true);
expect(screen.queryByRole("button", { name: "Remove unsaved source" })).toBeNull();
expect((button("Save & apply") as HTMLButtonElement).disabled).toBe(true);
});
it("reorders and disables a saved source, while discard restores its original fields and lock", async () => {
calls.getAuthSources.mockResolvedValue(settings([source(), source("custom", "CS")]));
page(); await ready();
await userEvent.click(screen.getAllByRole("button", { name: "Move source up" })[1]);
expect(field("Permanent source ID").value).toBe("custom");
await userEvent.click(screen.getAllByRole("checkbox", { name: "Enabled" })[0]);
await userEvent.click(button("Save & apply"));
await waitFor(() => expect(calls.setAuthSources).toHaveBeenCalledWith([{ ...source("custom", "CS"), enabled: false }, source()], "original"));
await waitFor(() => expect((button("Save & apply") as HTMLButtonElement).disabled).toBe(true));
fireEvent.change(field("Name collision prefix"), { target: { value: "NEW" } });
await userEvent.click(button("Discard changes"));
expect(field("Name collision prefix").value).toBe("CS");
expect(field("Permanent source ID").readOnly).toBe(true);
});
it("preserves a draft on conflict and lets the Owner discard then reload", async () => {
calls.setAuthSources.mockRejectedValue({ status: 409, code: "auth_sources_changed" });
page(); await ready();
fireEvent.change(field("Name collision prefix"), { target: { value: "NEW" } });
await userEvent.click(button("Save & apply"));
await screen.findByRole("alert");
expect(field("Name collision prefix").value).toBe("NEW");
expect((button("Reload") as HTMLButtonElement).disabled).toBe(true);
calls.getAuthSources.mockResolvedValue({ ...settings(), sources: [source("littleskin", "UP")], revision: "newest", managed: true });
await userEvent.click(button("Discard changes"));
await userEvent.click(button("Reload"));
await waitFor(() => expect(field("Name collision prefix").value).toBe("UP"));
});
it("tests unsaved endpoints without saving, reports unexpected status and clears stale results on edit", async () => {
page(); await ready();
fireEvent.change(field("Authentication endpoint (hasJoined)"), { target: { value: "https://new.example/check" } });
calls.testAuthSource.mockResolvedValueOnce({ ok: false, status: 200, elapsed_ms: 10 });
await userEvent.click(button("Test connection"));
await screen.findByText("Endpoint returned HTTP 200; expected 204 for an unused session.");
expect(calls.testAuthSource).toHaveBeenLastCalledWith({ ...source(), url: "https://new.example/check" });
expect(calls.setAuthSources).not.toHaveBeenCalled();
fireEvent.change(field("Authentication endpoint (hasJoined)"), { target: { value: "https://valid.example/check" } });
expect(screen.queryByRole("alert")).toBeNull();
await userEvent.click(button("Test connection"));
await screen.findByText("Authentication endpoint passed (18 ms).");
});
it("retries a failed initial load with the fields still visible and disabled", async () => {
calls.getAuthSources.mockRejectedValueOnce({ status: 503, code: "auth_sources_unavailable" });
page(); await screen.findByRole("alert");
expect(field("Permanent source ID").disabled).toBe(true);
await userEvent.click(button("Try again"));
await ready();
expect(field("Permanent source ID").value).toBe("littleskin");
});
it("supports installations with only the built-in source", async () => {
calls.getAuthSources.mockResolvedValue(settings([]));
page(); await screen.findByText("Only official accounts are enabled. Add a source to accept another provider.");
expect(screen.queryByLabelText("Permanent source ID")).toBeNull();
await userEvent.click(button("Add source"));
expect(field("Permanent source ID").readOnly).toBe(false);
expect((button("Save & apply") as HTMLButtonElement).disabled).toBe(true);
await userEvent.click(button("Remove unsaved source"));
expect((button("Save & apply") as HTMLButtonElement).disabled).toBe(true);
});
});
+151
View File
@@ -0,0 +1,151 @@
import { useEffect, useState } from "react";
import { ArrowDown, ArrowUp, Check, Loader2, Plus, RefreshCw, Save, ShieldCheck, Trash2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { PageHeader } from "@/components/PageHeader";
import { InlineError, MessageLine } from "@/components/MessageLine";
import { isReauthCancelled, useReauth } from "@/components/ReauthDialog";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { api, humanizeError } from "@/lib/api";
import { useAsync, useUnsavedGuard } from "@/lib/hooks";
import type { AuthSourceConfig, AuthSourcesSettings } from "@/lib/types";
import { cn } from "@/lib/utils";
const emptySource = (): AuthSourceConfig => ({ tag: "", prefix: "", url: "", api_url: "", enabled: true });
function validSource(source: AuthSourceConfig): boolean {
const endpoint = (value: string) => {
try {
const url = new URL(value);
return value.trim() === value && ["http:", "https:"].includes(url.protocol) && !!url.hostname && !/[?#]/.test(value);
} catch { return false; }
};
return !!source.tag && source.tag.trim() === source.tag && !source.tag.includes(":") && source.tag.toLowerCase() !== "mojang" &&
/^[a-z0-9]{1,4}$/i.test(source.prefix) && endpoint(source.url) && (!source.api_url || endpoint(source.api_url));
}
type SourceDraft = AuthSourceConfig & { locked?: boolean };
type Draft = Omit<AuthSourcesSettings, "sources"> & { sources: SourceDraft[]; original: string };
const wireSources = (sources: SourceDraft[]): AuthSourceConfig[] => sources.map(({ locked: _locked, ...source }) => source);
const loadedDraft = (settings: AuthSourcesSettings): Draft => ({ ...settings, sources: settings.sources.map((source) => ({ ...source, locked: true })), original: JSON.stringify(settings.sources) });
export function AuthSourcesPage() {
const { t } = useTranslation("authSources");
const query = useAsync(api.getAuthSources, []);
const reauth = useReauth();
const [draft, setDraft] = useState<Draft | null>(null);
const [saving, setSaving] = useState(false);
const [testing, setTesting] = useState<number | null>(null);
const [checks, setChecks] = useState<Record<number, { kind: "success" | "error"; text: string }>>({});
const [message, setMessage] = useState<{ kind: "success" | "error"; text: string } | null>(null);
useEffect(() => {
if (query.data) setDraft((current) => current && JSON.stringify(wireSources(current.sources)) !== current.original ? current : loadedDraft(query.data!));
}, [query.data]);
const dirty = draft !== null && JSON.stringify(wireSources(draft.sources)) !== draft.original;
useUnsavedGuard(dirty);
const busy = saving || testing !== null || query.loading;
const valid = draft !== null && draft.sources.every(validSource) &&
new Set(draft.sources.map((s) => s.tag)).size === draft.sources.length &&
new Set(draft.sources.map((s) => s.prefix.toLowerCase())).size === draft.sources.length;
function edit(sources: SourceDraft[]) {
setDraft((current) => current && { ...current, sources });
setChecks({});
setMessage(null);
}
function discard() {
if (!draft) return;
setDraft(loadedDraft({ ...draft, sources: JSON.parse(draft.original) as AuthSourceConfig[] }));
setChecks({});
setMessage(null);
}
async function save() {
if (!draft || !dirty || !valid || busy) return;
setSaving(true);
setMessage(null);
try {
const saved = await reauth.guard(() => api.setAuthSources(wireSources(draft.sources), draft.revision));
setDraft(loadedDraft(saved));
setMessage({ kind: "success", text: t("saved") });
} catch (error) {
if (!isReauthCancelled(error)) setMessage({ kind: "error", text: humanizeError(error) });
} finally { setSaving(false); }
}
async function testSource(index: number) {
if (!draft || busy || !validSource(draft.sources[index])) return;
setTesting(index);
try {
const result = await api.testAuthSource(wireSources(draft.sources)[index]);
setChecks((current) => ({ ...current, [index]: { kind: result.ok ? "success" : "error", text: result.ok ? t("test_ok", { ms: result.elapsed_ms }) : t("test_status", { status: result.status }) } }));
} catch (error) {
setChecks((current) => ({ ...current, [index]: { kind: "error", text: humanizeError(error) } }));
} finally { setTesting(null); }
}
return <div className="mx-auto w-full max-w-4xl space-y-5">
<PageHeader icon={ShieldCheck} title={t("title")} subtitle={t("subtitle")} />
<Card className="rounded-xl shadow-none"><CardContent className="flex items-start gap-3 pt-5">
<ShieldCheck className="mt-0.5 h-5 w-5 shrink-0 text-primary" />
<div className="space-y-1"><p className="text-sm font-semibold">{t("builtin_title")}</p><p className="text-xs leading-relaxed text-muted-foreground">{t("builtin_hint")}</p></div>
</CardContent></Card>
<div className="flex flex-wrap items-center justify-between gap-3">
<div><h2 className="text-sm font-semibold">{t("custom_title")}</h2><p className="mt-1 text-xs text-muted-foreground">{t("priority_hint")}</p></div>
<div className="flex gap-2">
<Button variant="outline" size="sm" disabled={!draft || dirty || busy || query.loading} onClick={query.reload}><RefreshCw className={cn(query.loading && "animate-spin")} />{t("reload")}</Button>
<Button size="sm" disabled={!draft || busy || draft.sources.length >= 32} onClick={() => draft && edit([...draft.sources, emptySource()])}><Plus />{t("add")}</Button>
</div>
</div>
{query.loading && <p role="status" className="flex items-center gap-2 text-sm text-muted-foreground"><Loader2 className="h-4 w-4 animate-spin" />{t("loading")}</p>}
{query.error != null && <div className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-destructive/30 bg-destructive/5 p-3"><InlineError message={humanizeError(query.error)} /><Button variant="outline" size="sm" disabled={dirty || busy} onClick={query.reload}>{t("common:try_again")}</Button></div>}
<div aria-busy={query.loading} className="space-y-4">
{(draft?.sources ?? [emptySource()]).map((source, index) => {
const locked = "locked" in source && source.locked === true;
const set = (patch: Partial<AuthSourceConfig>) => draft && edit(draft.sources.map((s, i) => i === index ? { ...s, ...patch } : s));
const move = (offset: number) => {
if (!draft) return;
const sources = [...draft.sources];
[sources[index], sources[index + offset]] = [sources[index + offset], sources[index]];
edit(sources);
};
return <Card key={index} className="overflow-hidden rounded-xl shadow-none">
<CardHeader className="flex-row flex-wrap items-center justify-between gap-3 space-y-0 border-b border-border/60 bg-muted/20 py-4">
<div className="flex min-w-0 flex-1 items-center gap-3"><span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-xs font-semibold text-primary">{index + 2}</span><CardTitle className="break-all text-sm">{source.tag || t(draft ? "new_source" : "loading")}</CardTitle></div>
<div className="flex items-center gap-2">
<label className="flex items-center gap-2 text-xs"><input type="checkbox" checked={draft !== null && source.enabled} onChange={(e) => set({ enabled: e.target.checked })} disabled={!draft || busy} className="h-4 w-4 accent-primary" />{t("enabled")}</label>
<Button variant="outline" size="icon" className="h-8 w-8" aria-label={t("move_up")} disabled={!draft || busy || index === 0} onClick={() => move(-1)}><ArrowUp /></Button>
<Button variant="outline" size="icon" className="h-8 w-8" aria-label={t("move_down")} disabled={!draft || busy || index === draft.sources.length - 1} onClick={() => move(1)}><ArrowDown /></Button>
{!locked && <Button variant="outline" size="icon" className="h-8 w-8" aria-label={t("remove")} disabled={!draft || busy} onClick={() => draft && edit(draft.sources.filter((_, i) => i !== index))}><Trash2 /></Button>}
</div>
</CardHeader>
<CardContent className="space-y-4 pt-5">
<div className="grid gap-4 sm:grid-cols-2">
<div className="space-y-2"><Label htmlFor={`source-tag-${index}`}>{t("tag")}</Label><Input id={`source-tag-${index}`} value={source.tag} readOnly={locked} disabled={!draft || busy} placeholder="littleskin" maxLength={128} onChange={(e) => set({ tag: e.target.value })} /><p className="text-xs text-muted-foreground">{t(locked ? "tag_locked" : "tag_hint")}</p></div>
<div className="space-y-2"><Label htmlFor={`source-prefix-${index}`}>{t("prefix")}</Label><Input id={`source-prefix-${index}`} value={source.prefix} disabled={!draft || busy} placeholder="LS" maxLength={4} onChange={(e) => set({ prefix: e.target.value })} /><p className="text-xs text-muted-foreground">{t("prefix_hint")}</p></div>
</div>
<div className="space-y-2"><Label htmlFor={`source-url-${index}`}>{t("url")}</Label><Input id={`source-url-${index}`} type="url" value={source.url} disabled={!draft || busy} placeholder="https://example.org/api/yggdrasil/sessionserver/session/minecraft/hasJoined" onChange={(e) => set({ url: e.target.value })} /><p className="text-xs text-muted-foreground">{t("url_hint")}</p></div>
<div className="space-y-2"><Label htmlFor={`source-api-${index}`}>{t("api_url")}</Label><Input id={`source-api-${index}`} type="url" value={source.api_url} disabled={!draft || busy} placeholder="https://example.org/api/yggdrasil" onChange={(e) => set({ api_url: e.target.value })} /><p className="text-xs text-muted-foreground">{t("api_hint")}</p></div>
<div className="flex flex-wrap items-center gap-3"><Button variant="outline" size="sm" disabled={!draft || busy || !validSource(source)} onClick={() => void testSource(index)}>{testing === index ? <Loader2 className="animate-spin" /> : <Check />}{t(testing === index ? "testing" : "test")}</Button><p className="text-xs text-muted-foreground">{t("test_hint")}</p></div>
{checks[index] && <MessageLine kind={checks[index].kind} message={checks[index].text} />}
</CardContent>
</Card>;
})}
{draft?.sources.length === 0 && <Card className="border-dashed shadow-none"><CardContent className="py-8 text-center text-sm text-muted-foreground">{t("empty")}</CardContent></Card>}
</div>
<p className="text-xs leading-relaxed text-muted-foreground">{t("disable_hint")}</p>
{message && <MessageLine kind={message.kind} message={message.text} />}
{draft && !valid && <InlineError message={t("invalid")} />}
<div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-border bg-card p-3">
<p className="text-xs text-muted-foreground">{draft ? t(dirty ? "unsaved" : draft.managed ? "active" : "defaults") : query.loading ? t("loading") : ""}</p>
<div className="flex gap-2">
{dirty && <Button variant="outline" disabled={busy} onClick={discard}>{t("discard")}</Button>}
<Button disabled={!dirty || !valid || busy} onClick={() => void save()}>{saving ? <Loader2 className="animate-spin" /> : <Save />}{t(saving ? "saving" : "save")}</Button>
</div>
</div>
{reauth.dialog}
</div>;
}