⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
feat(admin): create users and manage their credentials and avatars
Tina0055c7bc430
diff --git a/apps/api/src/admin/controllers/create-user.ts b/apps/api/src/admin/controllers/create-user.tsnew file mode 100644index 000000000..481c8eb6d--- /dev/null+++ b/apps/api/src/admin/controllers/create-user.ts@@ -0,0 +1,105 @@+import { eq, sql } from "drizzle-orm";+import db from "../../database";+import { userTable } from "../../database/schema";+import { ApiError } from "../../errors/api-error";+import { isCloud } from "../../utils/is-cloud";+import { isDisposableEmail } from "../../utils/is-disposable-email";+import type { AdminAuditRequest } from "../audit/admin-audit-request";+import { recordAdminAction } from "../audit/record-admin-action";+import { emailPasswordLink } from "../users/account-email-links";+import { adminUserColumns, toAdminUser } from "../users/admin-user-columns";+import { createsPasswordAccounts } from "../users/password-sign-in";++type CreateUserInput = {+ name: string;+ email: string;+ role: "admin" | "user";+};++export type PasswordSetupEmail =+ | "sent"+ | "failed"+ | "not_configured"+ | "not_needed";++function emailTaken() {+ return new ApiError(409, {+ code: "USER_ALREADY_EXISTS",+ message: "A user with this email address already exists.",+ });+}++/**+ * Create an account without a password. Where password sign-in is available,+ * the person gets a single-use link to choose one; otherwise the account is+ * meant for single sign-on, which needs a verified email to link to.+ */+async function createUser(input: CreateUserInput, audit: AdminAuditRequest) {+ const name = input.name.trim();+ const email = input.email.trim().toLowerCase();+ if (isCloud() && isDisposableEmail(email)) {+ throw new ApiError(400, {+ code: "DISPOSABLE_EMAIL_NOT_ALLOWED",+ message:+ "Use a permanent email address. Disposable addresses cannot create accounts.",+ });+ }+ const withPassword = createsPasswordAccounts();++ const userId = await db.transaction(async (tx) => {+ const [existing] = await tx+ .select({ id: userTable.id })+ .from(userTable)+ .where(eq(sql`lower(${userTable.email})`, email))+ .limit(1);+ if (existing) throw emailTaken();++ const [created] = await tx+ .insert(userTable)+ .values({ name, email, role: input.role, emailVerified: !withPassword })+ .onConflictDoNothing({ target: userTable.email })+ .returning({ id: userTable.id });+ if (!created) throw emailTaken();++ await recordAdminAction(+ {+ ...audit,+ action: "user.created",+ targetType: "user",+ targetId: created.id,+ targetLabel: email,+ metadata: {+ name,+ role: input.role,+ signIn: withPassword ? "password_link" : "single_sign_on",+ },+ },+ tx,+ );+ return created.id;+ });++ let passwordSetupEmail: PasswordSetupEmail = "not_needed";+ if (withPassword) {+ try {+ const result = await emailPasswordLink(+ { id: userId, name, email, locale: null },+ "setup",+ );+ passwordSetupEmail = result.success ? "sent" : "not_configured";+ } catch {+ passwordSetupEmail = "failed";+ }+ }++ const [row] = await db+ .select(adminUserColumns)+ .from(userTable)+ .where(eq(userTable.id, userId))+ .limit(1);+ if (!row)+ throw new ApiError(404, { code: "NOT_FOUND", message: "User not found" });+ return { user: toAdminUser(row), passwordSetupEmail };+}++export default createUser;diff --git a/apps/api/src/admin/controllers/list-users.ts b/apps/api/src/admin/controllers/list-users.tsindex b15640388..ca1d9ca89 100644--- a/apps/api/src/admin/controllers/list-users.ts+++ b/apps/api/src/admin/controllers/list-users.ts@@ -1,36 +1,51 @@-import { count, desc, ilike, or } from "drizzle-orm";+import { and, count, desc, eq, ilike, or, sql } from "drizzle-orm";import db from "../../database";import { userTable } from "../../database/schema";import { escapeLikePattern } from "../../search/like-pattern";+import { instanceAdminRoleSql } from "../../utils/instance-admin-role";+import { adminUserColumns, toAdminUser } from "../users/admin-user-columns";type ListUsersInput = {search?: string;+ status?: "active" | "deactivated";+ role?: "admin" | "user";+ emailVerified?: boolean;page: number;limit: number;};-export async function listUsers({ search, page, limit }: ListUsersInput) {+function filters({ search, status, role, emailVerified }: ListUsersInput) {const term = search?.trim() ?? "";const pattern = `%${escapeLikePattern(term)}%`;- const where = term- ? or(ilike(userTable.name, pattern), ilike(userTable.email, pattern))- : undefined;+ const deactivated = sql`coalesce(${userTable.banned}, false)`;+ const isAdmin = sql`coalesce(${instanceAdminRoleSql(userTable.role)}, false)`;+ return and(+ term+ ? or(ilike(userTable.name, pattern), ilike(userTable.email, pattern))+ : undefined,+ status === undefined+ ? undefined+ : status === "deactivated"+ ? deactivated+ : sql`NOT ${deactivated}`,+ role === undefined+ ? undefined+ : role === "admin"+ ? isAdmin+ : sql`NOT ${isAdmin}`,+ emailVerified === undefined+ ? undefined+ : eq(userTable.emailVerified, emailVerified),+ );+}++export async function listUsers(input: ListUsersInput) {+ const where = filters(input);+ const { page, limit } = input;const [rows, [totalRow]] = await Promise.all([db- .select({- id: userTable.id,- name: userTable.name,- email: userTable.email,- emailVerified: userTable.emailVerified,- image: userTable.image,- createdAt: userTable.createdAt,- updatedAt: userTable.updatedAt,- role: userTable.role,- banned: userTable.banned,- banReason: userTable.banReason,- banExpires: userTable.banExpires,- })+ .select(adminUserColumns).from(userTable).where(where).orderBy(desc(userTable.createdAt), desc(userTable.id))@@ -40,13 +55,7 @@ export async function listUsers({ search, page, limit }: ListUsersInput) {]);return {- users: rows.map((row) => ({- ...row,- createdAt: row.createdAt.toISOString(),- updatedAt: row.updatedAt.toISOString(),- banned: row.banned ?? false,- banExpires: row.banExpires ? row.banExpires.toISOString() : null,- })),+ users: rows.map(toAdminUser),total: totalRow?.value ?? 0,};}diff --git a/apps/api/src/admin/controllers/mark-email-verified.ts b/apps/api/src/admin/controllers/mark-email-verified.tsnew file mode 100644index 000000000..d6891b816--- /dev/null+++ b/apps/api/src/admin/controllers/mark-email-verified.ts@@ -0,0 +1,33 @@+import { and, eq } from "drizzle-orm";+import db from "../../database";+import { userTable } from "../../database/schema";+import type { AdminAuditRequest } from "../audit/admin-audit-request";+import { recordAdminAction } from "../audit/record-admin-action";+import { findAdminTargetUser } from "../users/find-admin-target-user";++/** Mark a user's email verified. Already verified addresses are left alone. */+async function markEmailVerified(userId: string, audit: AdminAuditRequest) {+ await db.transaction(async (tx) => {+ await findAdminTargetUser(userId, tx);+ const [updated] = await tx+ .update(userTable)+ .set({ emailVerified: true })+ .where(and(eq(userTable.id, userId), eq(userTable.emailVerified, false)))+ .returning({ email: userTable.email });+ if (!updated) return;++ await recordAdminAction(+ {+ ...audit,+ action: "user.email_verified",+ targetType: "user",+ targetId: userId,+ targetLabel: updated.email,+ },+ tx,+ );+ });+ return { emailVerified: true as const };+}++export default markEmailVerified;diff --git a/apps/api/src/admin/controllers/remove-user-avatar.ts b/apps/api/src/admin/controllers/remove-user-avatar.tsnew file mode 100644index 000000000..ecb86c232--- /dev/null+++ b/apps/api/src/admin/controllers/remove-user-avatar.ts@@ -0,0 +1,53 @@+import { eq } from "drizzle-orm";+import db from "../../database";+import { userAvatarTable, userTable } from "../../database/schema";+import { ApiError } from "../../errors/api-error";+import getManagedProfile from "../../user/controllers/get-managed-profile";+import {+ canRemoveAvatar,+ PROFILE_FIELD_MANAGED_BY_PROVIDER,+} from "../../user/managed-profile";+import type { AdminAuditRequest } from "../audit/admin-audit-request";+import { recordAdminAction } from "../audit/record-admin-action";+import { findAdminTargetUser } from "../users/find-admin-target-user";++/**+ * Remove a user's picture. A picture managed by the identity provider stays;+ * only an earlier Kaneo upload can be withdrawn, as in self-service.+ */+async function removeUserAvatar(userId: string, audit: AdminAuditRequest) {+ const managed = await getManagedProfile(userId);+ if (+ managed?.fields.includes("image") &&+ !canRemoveAvatar(managed.stored.image)+ ) {+ throw new ApiError(403, { ...PROFILE_FIELD_MANAGED_BY_PROVIDER });+ }++ return db.transaction(async (tx) => {+ const user = await findAdminTargetUser(userId, tx);+ const deleted = await tx+ .delete(userAvatarTable)+ .where(eq(userAvatarTable.userId, user.id))+ .returning({ id: userAvatarTable.id });+ if (user.image === null && deleted.length === 0) return { removed: false };++ await tx+ .update(userTable)+ .set({ image: null })+ .where(eq(userTable.id, user.id));+ await recordAdminAction(+ {+ ...audit,+ action: "user.avatar_removed",+ targetType: "user",+ targetId: user.id,+ targetLabel: user.email,+ },+ tx,+ );+ return { removed: true };+ });+}++export default removeUserAvatar;diff --git a/apps/api/src/admin/controllers/send-password-reset-email.ts b/apps/api/src/admin/controllers/send-password-reset-email.tsnew file mode 100644index 000000000..26986ae3c--- /dev/null+++ b/apps/api/src/admin/controllers/send-password-reset-email.ts@@ -0,0 +1,37 @@+import { ApiError } from "../../errors/api-error";+import type { AdminAuditRequest } from "../audit/admin-audit-request";+import { recordAdminAction } from "../audit/record-admin-action";+import { emailPasswordLink } from "../users/account-email-links";+import {+ assertEmailDeliverable,+ deliverOrThrow,+} from "../users/assert-email-deliverable";+import { findAdminTargetUser } from "../users/find-admin-target-user";+import { isPasswordSignInDisabled } from "../users/password-sign-in";++/** Email a user a link to choose a new password. The link is never returned. */+async function sendPasswordResetEmail(+ userId: string,+ audit: AdminAuditRequest,+) {+ const user = await findAdminTargetUser(userId);+ if (isPasswordSignInDisabled()) {+ throw new ApiError(409, {+ code: "PASSWORD_SIGN_IN_DISABLED",+ message: "Password sign-in is disabled on this instance.",+ });+ }+ assertEmailDeliverable(user);+ await deliverOrThrow(() => emailPasswordLink(user, "reset"));++ await recordAdminAction({+ ...audit,+ action: "user.password_reset_sent",+ targetType: "user",+ targetId: user.id,+ targetLabel: user.email,+ });+ return { sent: true as const };+}++export default sendPasswordResetEmail;diff --git a/apps/api/src/admin/controllers/send-verification-email.ts b/apps/api/src/admin/controllers/send-verification-email.tsnew file mode 100644index 000000000..2fd706114--- /dev/null+++ b/apps/api/src/admin/controllers/send-verification-email.ts@@ -0,0 +1,33 @@+import { ApiError } from "../../errors/api-error";+import type { AdminAuditRequest } from "../audit/admin-audit-request";+import { recordAdminAction } from "../audit/record-admin-action";+import { emailVerificationLink } from "../users/account-email-links";+import {+ assertEmailDeliverable,+ deliverOrThrow,+} from "../users/assert-email-deliverable";+import { findAdminTargetUser } from "../users/find-admin-target-user";++/** Email a user a link that confirms their address. */+async function sendVerificationEmail(userId: string, audit: AdminAuditRequest) {+ const user = await findAdminTargetUser(userId);+ if (user.emailVerified) {+ throw new ApiError(409, {+ code: "EMAIL_ALREADY_VERIFIED",+ message: "This email address is already verified.",+ });+ }+ assertEmailDeliverable(user);+ await deliverOrThrow(() => emailVerificationLink(user));++ await recordAdminAction({+ ...audit,+ action: "user.verification_sent",+ targetType: "user",+ targetId: user.id,+ targetLabel: user.email,+ });+ return { sent: true as const };+}++export default sendVerificationEmail;diff --git a/apps/api/src/admin/controllers/set-user-avatar.ts b/apps/api/src/admin/controllers/set-user-avatar.tsnew file mode 100644index 000000000..08287eab3--- /dev/null+++ b/apps/api/src/admin/controllers/set-user-avatar.ts@@ -0,0 +1,52 @@+import { eq } from "drizzle-orm";+import { HTTPException } from "hono/http-exception";+import db from "../../database";+import { userTable } from "../../database/schema";+import { ApiError } from "../../errors/api-error";+import { decodeAvatarUpload } from "../../user/avatar";+import saveAvatar from "../../user/controllers/save-avatar";+import getManagedProfile from "../../user/controllers/get-managed-profile";+import { PROFILE_FIELD_MANAGED_BY_PROVIDER } from "../../user/managed-profile";+import type { AdminAuditRequest } from "../audit/admin-audit-request";+import { recordAdminAction } from "../audit/record-admin-action";+import { findAdminTargetUser } from "../users/find-admin-target-user";++/** Upload a new avatar for a user, as they could themselves. */+async function setUserAvatar(+ input: { userId: string; contentType: string; data: string },+ audit: AdminAuditRequest,+) {+ const managed = await getManagedProfile(input.userId);+ if (managed?.fields.includes("image")) {+ throw new ApiError(403, { ...PROFILE_FIELD_MANAGED_BY_PROVIDER });+ }+ try {+ decodeAvatarUpload(input);+ } catch (error) {+ throw new HTTPException(400, {+ message: error instanceof Error ? error.message : "Invalid avatar upload",+ });+ }++ return db.transaction(async (tx) => {+ const user = await findAdminTargetUser(input.userId, tx);+ const avatar = await saveAvatar(input, tx);+ await tx+ .update(userTable)+ .set({ image: avatar.url })+ .where(eq(userTable.id, user.id));+ await recordAdminAction(+ {+ ...audit,+ action: "user.avatar_changed",+ targetType: "user",+ targetId: user.id,+ targetLabel: user.email,+ },+ tx,+ );+ return { image: avatar.url };+ });+}++export default setUserAvatar;diff --git a/apps/api/src/admin/index.ts b/apps/api/src/admin/index.tsindex f2a2ea017..e0a144d66 100644--- a/apps/api/src/admin/index.ts+++ b/apps/api/src/admin/index.ts@@ -16,6 +16,7 @@ import listWorkspaces from "./controllers/list-workspaces";import removeWorkspaceMember from "./controllers/remove-workspace-member";import transferWorkspaceOwnership from "./controllers/transfer-workspace-ownership";import updateWorkspaceMemberRole from "./controllers/update-workspace-member-role";+import adminUserRoutes from "./user-routes";import {adminAuditLogSchema,adminUserListSchema,@@ -45,7 +46,7 @@ const listUsersRoute = createRoute({tags: ["Admin"],summary: "List instance users",description:- "Page through every user account on this instance, optionally filtered by a case-insensitive name or email search. Requires an instance administrator session; API keys are rejected.",+ "Page through every user account on this instance, newest first, optionally filtered by a case-insensitive name or email search, status, instance role, and email verification. Each user lists their linked sign-in methods and last session activity. Requires an instance administrator session; API keys are rejected.",middleware: [requireUserSession, requireInstanceAdmin] as const,request: { query: listAdminUsersQuery },responses: {@@ -288,6 +289,7 @@ const admin = apiRouter()).openapi(listAuditLogRoute, async (c) =>c.json(await listAuditLog(c.req.valid("query")), 200),- );+ )+ .route("/users", adminUserRoutes);export default admin;diff --git a/apps/api/src/admin/response.ts b/apps/api/src/admin/response.tsindex 93c504818..aed93baa1 100644--- a/apps/api/src/admin/response.ts+++ b/apps/api/src/admin/response.ts@@ -15,6 +15,14 @@ export const adminUserSchema = zbanned: z.boolean(),banReason: z.string().nullable(),banExpires: isoTimestamp.nullable(),+ lastActiveAt: isoTimestamp.nullable().openapi({+ description:+ "When one of the user's current sessions was last refreshed; null without a session.",+ }),+ signInMethods: z.array(z.string()).openapi({+ description:+ "Linked sign-in methods: `credential` (password), `github`, `google`, `discord`, or `custom` (OIDC).",+ }),}).openapi("AdminUser");@@ -107,3 +115,35 @@ export const adminAuditLogSchema = z}),}).openapi("AdminAuditLog");++export const createdAdminUserSchema = z+ .object({+ user: adminUserSchema,+ passwordSetupEmail: z+ .enum(["sent", "failed", "not_configured", "not_needed"])+ .openapi({+ description:+ "Whether the link to choose a password was emailed: `not_configured` without SMTP, `not_needed` when the account is for single sign-on. The link itself is never returned.",+ }),+ })+ .openapi("CreatedAdminUser");++export const adminEmailSentSchema = z+ .object({ sent: z.literal(true) })+ .openapi("AdminEmailSent");++export const adminEmailVerifiedSchema = z+ .object({ emailVerified: z.literal(true) })+ .openapi("AdminEmailVerified");++export const adminUserAvatarSchema = z+ .object({ image: z.string() })+ .openapi("AdminUserAvatar");++export const adminUserAvatarRemovedSchema = z+ .object({+ removed: z.boolean().openapi({+ description: "False when the user had no picture to remove.",+ }),+ })+ .openapi("AdminUserAvatarRemoved");diff --git a/apps/api/src/admin/schema.ts b/apps/api/src/admin/schema.tsindex c86f89f6f..caab8f18d 100644--- a/apps/api/src/admin/schema.ts+++ b/apps/api/src/admin/schema.ts@@ -4,6 +4,21 @@ export const listAdminUsersQuery = z.object({search: z.string().max(200).optional().openapi({description: "Case-insensitive match against user name or email.",}),+ status: z.enum(["active", "deactivated"]).optional().openapi({+ description: "Only active or only deactivated accounts.",+ }),+ role: z.enum(["admin", "user"]).optional().openapi({+ description: "Only instance administrators, or only everyone else.",+ }),+ emailVerified: z+ .enum(["true", "false"])+ .transform((value) => value === "true")+ .optional()+ .openapi({+ type: "string",+ enum: ["true", "false"],+ description: "Only users whose email is verified, or is not.",+ }),page: pagingNumber(1, 1_000_000, 1),limit: pagingNumber(1, 100, 20),});@@ -66,3 +81,16 @@ export const listAdminAuditLogQuery = z.object({page: pagingNumber(1, 1_000_000, 1),limit: pagingNumber(1, 100, 25),});++export const adminUserParam = z.object({ userId: z.string().min(1) });++export const createAdminUserBody = z.object({+ name: z.string().trim().min(1).max(200),+ email: z.email().max(254).openapi({+ description:+ "The new user's email address. They sign in with it and receive their password link there.",+ }),+ role: z.enum(["admin", "user"]).default("user").openapi({+ description: "Instance role: `admin` administers the instance.",+ }),+});diff --git a/apps/api/src/admin/user-routes.ts b/apps/api/src/admin/user-routes.tsnew file mode 100644index 000000000..84f4acd50--- /dev/null+++ b/apps/api/src/admin/user-routes.ts@@ -0,0 +1,214 @@+import {+ apiRouter,+ createRoute,+ errorResponse,+ jsonResponse,+} from "../openapi";+import { MAX_AVATAR_BYTES, MAX_AVATAR_REQUEST_BYTES } from "../user/avatar";+import { uploadAvatarBody } from "../user/schema";+import { boundedRequestBody } from "../utils/bounded-request-body";+import { requireInstanceAdmin } from "../utils/require-instance-admin";+import { requireUserSession } from "../utils/require-user-session";+import { adminAuditRequest } from "./audit/admin-audit-request";+import createUser from "./controllers/create-user";+import markEmailVerified from "./controllers/mark-email-verified";+import removeUserAvatar from "./controllers/remove-user-avatar";+import sendPasswordResetEmail from "./controllers/send-password-reset-email";+import sendVerificationEmail from "./controllers/send-verification-email";+import setUserAvatar from "./controllers/set-user-avatar";+import {+ adminEmailSentSchema,+ adminEmailVerifiedSchema,+ adminUserAvatarRemovedSchema,+ adminUserAvatarSchema,+ createdAdminUserSchema,+} from "./response";+import { adminUserParam, createAdminUserBody } from "./schema";++const forbidden = errorResponse(+ "The caller is not an instance administrator or is authenticated with an API key",+);+const notFound = errorResponse("User not found");+const emailErrors = {+ 409: errorResponse(+ "Nothing to send: a guest account, an already verified address, or password sign-in is disabled",+ ),+ 502: errorResponse("The SMTP server did not accept the email"),+ 503: errorResponse("Email delivery is not configured on this instance"),+};++const createUserRoute = createRoute({+ method: "post",+ operationId: "createAdminUser",+ path: "/",+ tags: ["Admin"],+ summary: "Create a user",+ description:+ "Create an account with an instance role. No password is set or returned. When password sign-in is available, the user is emailed a single-use link, valid for 2 days, to choose their own password. When password registration or the login form is disabled, the account is created with a verified email so the user can sign in with single sign-on, and no email is sent. Registration restrictions do not apply to administrators.",+ middleware: [requireUserSession, requireInstanceAdmin] as const,+ request: {+ body: {+ required: true,+ content: { "application/json": { schema: createAdminUserBody } },+ },+ },+ responses: {+ 201: jsonResponse("The new user", createdAdminUserSchema),+ 400: errorResponse("Invalid name, email, or role, or a disposable address"),+ 403: forbidden,+ 409: errorResponse("A user with this email already exists"),+ },+});++const sendPasswordResetRoute = createRoute({+ method: "post",+ operationId: "sendAdminUserPasswordReset",+ path: "/{userId}/password-reset-email",+ tags: ["Admin"],+ summary: "Email a password reset link",+ description:+ "Email the user a single-use link to choose a new password, using the regular reset lifetime. The link is never returned to the administrator.",+ middleware: [requireUserSession, requireInstanceAdmin] as const,+ request: { params: adminUserParam },+ responses: {+ 200: jsonResponse("The email was sent", adminEmailSentSchema),+ 403: forbidden,+ 404: notFound,+ ...emailErrors,+ },+});++const sendVerificationRoute = createRoute({+ method: "post",+ operationId: "sendAdminUserVerificationEmail",+ path: "/{userId}/verification-email",+ tags: ["Admin"],+ summary: "Email a verification link",+ description:+ "Email the user a link, valid for 24 hours, that confirms their email address. The link is never returned to the administrator.",+ middleware: [requireUserSession, requireInstanceAdmin] as const,+ request: { params: adminUserParam },+ responses: {+ 200: jsonResponse("The email was sent", adminEmailSentSchema),+ 403: forbidden,+ 404: notFound,+ ...emailErrors,+ },+});++const markEmailVerifiedRoute = createRoute({+ method: "put",+ operationId: "markAdminUserEmailVerified",+ path: "/{userId}/email-verified",+ tags: ["Admin"],+ summary: "Mark an email as verified",+ description:+ "Mark the user's email address as verified without asking them, for example so a single sign-on identity with the same address can link to the account.",+ middleware: [requireUserSession, requireInstanceAdmin] as const,+ request: { params: adminUserParam },+ responses: {+ 200: jsonResponse("The email is verified", adminEmailVerifiedSchema),+ 403: forbidden,+ 404: notFound,+ },+});++const setAvatarRoute = createRoute({+ method: "put",+ operationId: "setAdminUserAvatar",+ path: "/{userId}/avatar",+ tags: ["Admin"],+ summary: "Set a user's avatar",+ description: `Store a base64 encoded avatar (PNG, JPEG, or WebP, up to ${Math.floor(+ MAX_AVATAR_BYTES / 1024,+ )}KB) for the user and make it their profile picture. Not available when the identity provider manages the user's picture.`,+ middleware: [+ requireUserSession,+ requireInstanceAdmin,+ boundedRequestBody(MAX_AVATAR_REQUEST_BYTES),+ ] as const,+ request: {+ params: adminUserParam,+ body: {+ required: true,+ content: { "application/json": { schema: uploadAvatarBody } },+ },+ },+ responses: {+ 200: jsonResponse("The new picture", adminUserAvatarSchema),+ 400: errorResponse("Unsupported, invalid, or oversized image"),+ 403: errorResponse(+ "Not an instance administrator, an API key, or the picture is managed by the identity provider",+ ),+ 404: notFound,+ 413: errorResponse("Request body is too large"),+ },+});++const removeAvatarRoute = createRoute({+ method: "delete",+ operationId: "removeAdminUserAvatar",+ path: "/{userId}/avatar",+ tags: ["Admin"],+ summary: "Remove a user's avatar",+ description:+ "Remove the user's profile picture. A picture managed by the identity provider can't be removed, but an earlier Kaneo upload can.",+ middleware: [requireUserSession, requireInstanceAdmin] as const,+ request: { params: adminUserParam },+ responses: {+ 200: jsonResponse("Picture removed", adminUserAvatarRemovedSchema),+ 403: errorResponse(+ "Not an instance administrator, an API key, or the picture is managed by the identity provider",+ ),+ 404: notFound,+ },+});++const adminUserRoutes = apiRouter()+ .openapi(createUserRoute, async (c) =>+ c.json(await createUser(c.req.valid("json"), adminAuditRequest(c)), 201),+ )+ .openapi(sendPasswordResetRoute, async (c) =>+ c.json(+ await sendPasswordResetEmail(+ c.req.valid("param").userId,+ adminAuditRequest(c),+ ),+ 200,+ ),+ )+ .openapi(sendVerificationRoute, async (c) =>+ c.json(+ await sendVerificationEmail(+ c.req.valid("param").userId,+ adminAuditRequest(c),+ ),+ 200,+ ),+ )+ .openapi(markEmailVerifiedRoute, async (c) =>+ c.json(+ await markEmailVerified(+ c.req.valid("param").userId,+ adminAuditRequest(c),+ ),+ 200,+ ),+ )+ .openapi(setAvatarRoute, async (c) =>+ c.json(+ await setUserAvatar(+ { userId: c.req.valid("param").userId, ...c.req.valid("json") },+ adminAuditRequest(c),+ ),+ 200,+ ),+ )+ .openapi(removeAvatarRoute, async (c) =>+ c.json(+ await removeUserAvatar(c.req.valid("param").userId, adminAuditRequest(c)),+ 200,+ ),+ );++export default adminUserRoutes;diff --git a/apps/api/src/admin/users/account-email-links.ts b/apps/api/src/admin/users/account-email-links.tsnew file mode 100644index 000000000..83f815e59--- /dev/null+++ b/apps/api/src/admin/users/account-email-links.ts@@ -0,0 +1,87 @@+import { randomBytes } from "node:crypto";+import {+ type AccountPasswordPurpose,+ type EmailResult,+ isSmtpConfigured,+ sendAccountPasswordEmail,+ sendEmailVerificationEmail,+} from "@kaneo/email";+import { createEmailVerificationToken } from "better-auth/api";+import { auth } from "../../auth";+import { accountEmailSubject } from "./account-email-subjects";+import type { AdminTargetUser } from "./find-admin-target-user";++// A new account has longer to act on its first email than a reset link.+const SETUP_LINK_SECONDS = 2 * 24 * 60 * 60;+const VERIFICATION_LINK_SECONDS = 24 * 60 * 60;++type Recipient = Pick<AdminTargetUser, "id" | "name" | "email" | "locale">;++const notConfigured: EmailResult = {+ success: false,+ reason: "SMTP_NOT_CONFIGURED",+};++function clientUrl(path: string) {+ const base = process.env.KANEO_CLIENT_URL || "http://localhost:5173";+ return encodeURIComponent(`${base.replace(/\/$/, "")}${path}`);+}++/**+ * Email a link to choose a password, using the same single-use token and+ * `/reset-password` flow as self-service resets. The link is never returned.+ * Throws when the SMTP server rejects the message.+ */+export async function emailPasswordLink(+ user: Recipient,+ purpose: AccountPasswordPurpose,+): Promise<EmailResult> {+ if (!isSmtpConfigured()) return notConfigured;+ const context = await auth.$context;+ const seconds =+ purpose === "setup"+ ? SETUP_LINK_SECONDS+ : (context.options.emailAndPassword?.resetPasswordTokenExpiresIn ?? 3600);+ const token = randomBytes(18).toString("base64url");+ await context.internalAdapter.createVerificationValue({+ identifier: `reset-password:${token}`,+ value: user.id,+ expiresAt: new Date(Date.now() + seconds * 1000),+ });+ return sendAccountPasswordEmail(+ user.email,+ accountEmailSubject(purpose, user.locale),+ {+ purpose,+ passwordLink: `${context.baseURL}/reset-password/${token}?callbackURL=${clientUrl("/auth/reset-password")}`,+ userName: user.name,+ locale: user.locale,+ },+ );+}++/**+ * Email a link that marks the address verified through better-auth's+ * `/verify-email` endpoint. Throws when the SMTP server rejects the message.+ */+export async function emailVerificationLink(+ user: Recipient,+): Promise<EmailResult> {+ if (!isSmtpConfigured()) return notConfigured;+ const context = await auth.$context;+ const token = await createEmailVerificationToken(+ context.secret,+ user.email,+ undefined,+ VERIFICATION_LINK_SECONDS,+ );+ return sendEmailVerificationEmail(+ user.email,+ accountEmailSubject("verification", user.locale),+ {+ verificationLink: `${context.baseURL}/verify-email?token=${token}&callbackURL=${clientUrl("/auth/sign-in")}`,+ userName: user.name,+ locale: user.locale,+ },+ );+}diff --git a/apps/api/src/admin/users/account-email-subjects.ts b/apps/api/src/admin/users/account-email-subjects.tsnew file mode 100644index 000000000..b4b8ea152--- /dev/null+++ b/apps/api/src/admin/users/account-email-subjects.ts@@ -0,0 +1,44 @@+import type { AccountPasswordPurpose } from "@kaneo/email";++type Subjects = Record<AccountPasswordPurpose | "verification", string>;++const subjects = {+ en: {+ setup: "Set up your Kaneo account",+ reset: "Choose a new Kaneo password",+ verification: "Confirm your email address for Kaneo",+ },+ de: {+ setup: "Richte dein Kaneo-Konto ein",+ reset: "Lege ein neues Kaneo-Passwort fest",+ verification: "Bestätige deine E-Mail-Adresse für Kaneo",+ },+ vi: {+ setup: "Thiết lập tài khoản Kaneo",+ reset: "Đặt mật khẩu Kaneo mới",+ verification: "Xác nhận địa chỉ email cho Kaneo",+ },+ ja: {+ setup: "Kaneo アカウントの設定",+ reset: "Kaneo の新しいパスワードを設定",+ verification: "Kaneo のメールアドレスを確認",+ },+ "zh-tw": {+ setup: "設定你的 Kaneo 帳號",+ reset: "設定新的 Kaneo 密碼",+ verification: "確認你的 Kaneo 電子郵件地址",+ },+} satisfies Record<string, Subjects>;++export function accountEmailSubject(+ kind: keyof Subjects,+ locale: string | null,+) {+ const normalized = locale?.toLowerCase() ?? "";+ const key = normalized === "zh-tw" ? normalized : normalized.split("-")[0];+ const copy: Subjects =+ key && key in subjects+ ? subjects[key as keyof typeof subjects]+ : subjects.en;+ return copy[kind];+}diff --git a/apps/api/src/admin/users/admin-user-columns.ts b/apps/api/src/admin/users/admin-user-columns.tsnew file mode 100644index 000000000..8e285b496--- /dev/null+++ b/apps/api/src/admin/users/admin-user-columns.ts@@ -0,0 +1,54 @@+import { sql } from "drizzle-orm";+import { userTable } from "../../database/schema";++/**+ * Columns of an admin directory row. Last activity and sign-in methods are+ * correlated subqueries on indexed user ids, evaluated only for the page.+ * Columns are qualified by hand: Drizzle leaves them bare in one-table selects.+ * Timestamps are stored as UTC without a zone; say so, or the driver reads+ * them in the server's local time.+ */+export const adminUserColumns = {+ id: userTable.id,+ name: userTable.name,+ email: userTable.email,+ emailVerified: userTable.emailVerified,+ image: userTable.image,+ createdAt: userTable.createdAt,+ updatedAt: userTable.updatedAt,+ role: userTable.role,+ banned: userTable.banned,+ banReason: userTable.banReason,+ banExpires: userTable.banExpires,+ lastActiveAt: sql<Date | string | null>`(+ SELECT max(s."updated_at") AT TIME ZONE 'UTC'+ FROM "session" s WHERE s."user_id" = "user"."id"+ )`,+ signInMethods: sql<string[]>`(+ SELECT coalesce(array_agg(DISTINCT a."provider_id"), '{}')+ FROM "account" a WHERE a."user_id" = "user"."id"+ )`,+};++type AdminUserRow = {+ [Key in keyof typeof adminUserColumns]: Key extends "lastActiveAt"+ ? Date | string | null+ : Key extends "signInMethods"+ ? string[]+ : (typeof userTable.$inferSelect)[Key &+ keyof typeof userTable.$inferSelect];+};++const iso = (value: Date | string) => new Date(value).toISOString();++export function toAdminUser(row: AdminUserRow) {+ return {+ ...row,+ createdAt: iso(row.createdAt),+ updatedAt: iso(row.updatedAt),+ banned: row.banned ?? false,+ banExpires: row.banExpires ? iso(row.banExpires) : null,+ lastActiveAt: row.lastActiveAt ? iso(row.lastActiveAt) : null,+ signInMethods: [...row.signInMethods].sort(),+ };+}diff --git a/apps/api/src/admin/users/assert-email-deliverable.ts b/apps/api/src/admin/users/assert-email-deliverable.tsnew file mode 100644index 000000000..754c521f4--- /dev/null+++ b/apps/api/src/admin/users/assert-email-deliverable.ts@@ -0,0 +1,36 @@+import { type EmailResult, isSmtpConfigured } from "@kaneo/email";+import { ApiError } from "../../errors/api-error";+import type { AdminTargetUser } from "./find-admin-target-user";++/** Guests have generated addresses, and nothing can be sent without SMTP. */+export function assertEmailDeliverable(user: AdminTargetUser) {+ if (user.isAnonymous) {+ throw new ApiError(409, {+ code: "GUEST_ACCOUNT",+ message: "Guest accounts have no email address to send to.",+ });+ }+ if (!isSmtpConfigured()) throw notConfigured();+}++function notConfigured() {+ return new ApiError(503, {+ code: "EMAIL_DELIVERY_NOT_CONFIGURED",+ message:+ "Email delivery is not configured on this instance. Configure SMTP to send emails.",+ });+}++export async function deliverOrThrow(send: () => Promise<EmailResult>) {+ let result: EmailResult;+ try {+ result = await send();+ } catch {+ throw new ApiError(502, {+ code: "EMAIL_DELIVERY_FAILED",+ message:+ "The email could not be sent. Check the SMTP settings and try again.",+ });+ }+ if (!result.success) throw notConfigured();+}diff --git a/apps/api/src/admin/users/find-admin-target-user.ts b/apps/api/src/admin/users/find-admin-target-user.tsnew file mode 100644index 000000000..3df9b02e9--- /dev/null+++ b/apps/api/src/admin/users/find-admin-target-user.ts@@ -0,0 +1,29 @@+import { eq } from "drizzle-orm";+import { HTTPException } from "hono/http-exception";+import db from "../../database";+import { userTable } from "../../database/schema";+import type { DbOrTx } from "../../project-access/db-or-tx";++/** The user an admin action is about, or a 404. */+export async function findAdminTargetUser(+ userId: string,+ database: DbOrTx = db,+) {+ const [user] = await database+ .select({+ id: userTable.id,+ name: userTable.name,+ email: userTable.email,+ emailVerified: userTable.emailVerified,+ image: userTable.image,+ locale: userTable.locale,+ isAnonymous: userTable.isAnonymous,+ })+ .from(userTable)+ .where(eq(userTable.id, userId))+ .limit(1);+ if (!user) throw new HTTPException(404, { message: "User not found" });+ return user;+}++export type AdminTargetUser = Awaited<ReturnType<typeof findAdminTargetUser>>;diff --git a/apps/api/src/admin/users/password-sign-in.ts b/apps/api/src/admin/users/password-sign-in.tsnew file mode 100644index 000000000..1d2526820--- /dev/null+++ b/apps/api/src/admin/users/password-sign-in.ts@@ -0,0 +1,17 @@+// Read at call time so tests can stub the environment.++/** Local password sign-in is turned off entirely. */+export function isPasswordSignInDisabled() {+ return process.env.DISABLE_LOGIN_FORM === "true";+}++/**+ * Whether a new account gets a link to choose a password. When password sign-in+ * or password registration is off, accounts are created for single sign-on.+ */+export function createsPasswordAccounts() {+ return (+ !isPasswordSignInDisabled() &&+ process.env.DISABLE_PASSWORD_REGISTRATION !== "true"+ );+}diff --git a/apps/api/src/user/controllers/save-avatar.ts b/apps/api/src/user/controllers/save-avatar.tsindex a517bc01b..a37945a59 100644--- a/apps/api/src/user/controllers/save-avatar.ts+++ b/apps/api/src/user/controllers/save-avatar.ts@@ -1,20 +1,24 @@import { createId } from "@paralleldrive/cuid2";import db from "../../database";import { userAvatarTable } from "../../database/schema";+import type { DbOrTx } from "../../project-access/db-or-tx";import { buildAvatarUrl, decodeAvatarUpload } from "../avatar";-export async function saveAvatar({- userId,- contentType,- data,-}: {- userId: string;- contentType: string;- data: string;-}) {+export async function saveAvatar(+ {+ userId,+ contentType,+ data,+ }: {+ userId: string;+ contentType: string;+ data: string;+ },+ database: DbOrTx = db,+) {const { mimeType, bytes } = decodeAvatarUpload({ contentType, data });- const [saved] = await db+ const [saved] = await database.insert(userAvatarTable).values({userId,diff --git a/apps/docs/openapi.json b/apps/docs/openapi.jsonindex 0f6a73de7..c0e4856d8 100644--- a/apps/docs/openapi.json+++ b/apps/docs/openapi.json@@ -5391,6 +5391,21 @@"null"],"format": "date-time"+ },+ "lastActiveAt": {+ "type": [+ "string",+ "null"+ ],+ "format": "date-time",+ "description": "When one of the user's current sessions was last refreshed; null without a session."+ },+ "signInMethods": {+ "type": "array",+ "items": {+ "type": "string"+ },+ "description": "Linked sign-in methods: `credential` (password), `github`, `google`, `discord`, or `custom` (OIDC)."}},"required": [@@ -5404,7 +5419,9 @@"role","banned","banReason",- "banExpires"+ "banExpires",+ "lastActiveAt",+ "signInMethods"]},"AdminWorkspaceList": {@@ -5626,6 +5643,79 @@"ipAddress","userAgent"]+ },+ "CreatedAdminUser": {+ "type": "object",+ "properties": {+ "user": {+ "$ref": "#/components/schemas/AdminUser"+ },+ "passwordSetupEmail": {+ "type": "string",+ "enum": [+ "sent",+ "failed",+ "not_configured",+ "not_needed"+ ],+ "description": "Whether the link to choose a password was emailed: `not_configured` without SMTP, `not_needed` when the account is for single sign-on. The link itself is never returned."+ }+ },+ "required": [+ "user",+ "passwordSetupEmail"+ ]+ },+ "AdminEmailSent": {+ "type": "object",+ "properties": {+ "sent": {+ "type": "boolean",+ "enum": [+ true+ ]+ }+ },+ "required": [+ "sent"+ ]+ },+ "AdminEmailVerified": {+ "type": "object",+ "properties": {+ "emailVerified": {+ "type": "boolean",+ "enum": [+ true+ ]+ }+ },+ "required": [+ "emailVerified"+ ]+ },+ "AdminUserAvatar": {+ "type": "object",+ "properties": {+ "image": {+ "type": "string"+ }+ },+ "required": [+ "image"+ ]+ },+ "AdminUserAvatarRemoved": {+ "type": "object",+ "properties": {+ "removed": {+ "type": "boolean",+ "description": "False when the user had no picture to remove."+ }+ },+ "required": [+ "removed"+ ]}},"parameters": {}@@ -24096,7 +24186,7 @@"Admin"],"summary": "List instance users",- "description": "Page through every user account on this instance, optionally filtered by a case-insensitive name or email search. Requires an instance administrator session; API keys are rejected.",+ "description": "Page through every user account on this instance, newest first, optionally filtered by a case-insensitive name or email search, status, instance role, and email verification. Each user lists their linked sign-in methods and last session activity. Requires an instance administrator session; API keys are rejected.","parameters": [{"schema": {@@ -24109,6 +24199,48 @@"name": "search","in": "query"},+ {+ "schema": {+ "type": "string",+ "enum": [+ "active",+ "deactivated"+ ],+ "description": "Only active or only deactivated accounts."+ },+ "required": false,+ "description": "Only active or only deactivated accounts.",+ "name": "status",+ "in": "query"+ },+ {+ "schema": {+ "type": "string",+ "enum": [+ "admin",+ "user"+ ],+ "description": "Only instance administrators, or only everyone else."+ },+ "required": false,+ "description": "Only instance administrators, or only everyone else.",+ "name": "role",+ "in": "query"+ },+ {+ "schema": {+ "type": "string",+ "enum": [+ "true",+ "false"+ ],+ "description": "Only users whose email is verified, or is not."+ },+ "required": false,+ "description": "Only users whose email is verified, or is not.",+ "name": "emailVerified",+ "in": "query"+ },{"schema": {"type": "integer",@@ -24177,6 +24309,105 @@"$ref": "#/components/responses/ApiKeyRateLimited"}}+ },+ "post": {+ "operationId": "createAdminUser",+ "tags": [+ "Admin"+ ],+ "summary": "Create a user",+ "description": "Create an account with an instance role. No password is set or returned. When password sign-in is available, the user is emailed a single-use link, valid for 2 days, to choose their own password. When password registration or the login form is disabled, the account is created with a verified email so the user can sign in with single sign-on, and no email is sent. Registration restrictions do not apply to administrators.",+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "minLength": 1,+ "maxLength": 200+ },+ "email": {+ "type": "string",+ "maxLength": 254,+ "format": "email",+ "description": "The new user's email address. They sign in with it and receive their password link there."+ },+ "role": {+ "type": "string",+ "enum": [+ "admin",+ "user"+ ],+ "default": "user",+ "description": "Instance role: `admin` administers the instance."+ }+ },+ "required": [+ "name",+ "email"+ ]+ }+ }+ }+ },+ "responses": {+ "201": {+ "description": "The new user",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CreatedAdminUser"+ }+ }+ }+ },+ "400": {+ "description": "Invalid name, email, or role, or a disposable address",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "403": {+ "description": "The caller is not an instance administrator or is authenticated with an API key",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "409": {+ "description": "A user with this email already exists",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"+ }+ }}},"/admin/workspaces": {@@ -24942,6 +25173,441 @@}}}+ },+ "/admin/users/{userId}/password-reset-email": {+ "post": {+ "operationId": "sendAdminUserPasswordReset",+ "tags": [+ "Admin"+ ],+ "summary": "Email a password reset link",+ "description": "Email the user a single-use link to choose a new password, using the regular reset lifetime. The link is never returned to the administrator.",+ "parameters": [+ {+ "schema": {+ "type": "string",+ "minLength": 1+ },+ "required": true,+ "name": "userId",+ "in": "path"+ }+ ],+ "responses": {+ "200": {+ "description": "The email was sent",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AdminEmailSent"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "403": {+ "description": "The caller is not an instance administrator or is authenticated with an API key",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "404": {+ "description": "User not found",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "409": {+ "description": "Nothing to send: a guest account, an already verified address, or password sign-in is disabled",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"+ },+ "502": {+ "description": "The SMTP server did not accept the email",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "503": {+ "description": "Email delivery is not configured on this instance",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ }+ }+ }+ },+ "/admin/users/{userId}/verification-email": {+ "post": {+ "operationId": "sendAdminUserVerificationEmail",+ "tags": [+ "Admin"+ ],+ "summary": "Email a verification link",+ "description": "Email the user a link, valid for 24 hours, that confirms their email address. The link is never returned to the administrator.",+ "parameters": [+ {+ "schema": {+ "type": "string",+ "minLength": 1+ },+ "required": true,+ "name": "userId",+ "in": "path"+ }+ ],+ "responses": {+ "200": {+ "description": "The email was sent",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AdminEmailSent"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "403": {+ "description": "The caller is not an instance administrator or is authenticated with an API key",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "404": {+ "description": "User not found",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "409": {+ "description": "Nothing to send: a guest account, an already verified address, or password sign-in is disabled",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"+ },+ "502": {+ "description": "The SMTP server did not accept the email",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "503": {+ "description": "Email delivery is not configured on this instance",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ }+ }+ }+ },+ "/admin/users/{userId}/email-verified": {+ "put": {+ "operationId": "markAdminUserEmailVerified",+ "tags": [+ "Admin"+ ],+ "summary": "Mark an email as verified",+ "description": "Mark the user's email address as verified without asking them, for example so a single sign-on identity with the same address can link to the account.",+ "parameters": [+ {+ "schema": {+ "type": "string",+ "minLength": 1+ },+ "required": true,+ "name": "userId",+ "in": "path"+ }+ ],+ "responses": {+ "200": {+ "description": "The email is verified",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AdminEmailVerified"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "403": {+ "description": "The caller is not an instance administrator or is authenticated with an API key",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "404": {+ "description": "User not found",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"+ }+ }+ }+ },+ "/admin/users/{userId}/avatar": {+ "put": {+ "operationId": "setAdminUserAvatar",+ "tags": [+ "Admin"+ ],+ "summary": "Set a user's avatar",+ "description": "Store a base64 encoded avatar (PNG, JPEG, or WebP, up to 512KB) for the user and make it their profile picture. Not available when the identity provider manages the user's picture.",+ "parameters": [+ {+ "schema": {+ "type": "string",+ "minLength": 1+ },+ "required": true,+ "name": "userId",+ "in": "path"+ }+ ],+ "requestBody": {+ "required": true,+ "content": {+ "application/json": {+ "schema": {+ "type": "object",+ "properties": {+ "contentType": {+ "type": "string",+ "maxLength": 64,+ "description": "One of image/png, image/jpeg, or image/webp.",+ "example": "image/png"+ },+ "data": {+ "type": "string",+ "maxLength": 700076,+ "description": "Base64 encoded image bytes."+ }+ },+ "required": [+ "contentType",+ "data"+ ]+ }+ }+ }+ },+ "responses": {+ "200": {+ "description": "The new picture",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AdminUserAvatar"+ }+ }+ }+ },+ "400": {+ "description": "Unsupported, invalid, or oversized image",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "403": {+ "description": "Not an instance administrator, an API key, or the picture is managed by the identity provider",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "404": {+ "description": "User not found",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "413": {+ "description": "Request body is too large",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"+ }+ }+ },+ "delete": {+ "operationId": "removeAdminUserAvatar",+ "tags": [+ "Admin"+ ],+ "summary": "Remove a user's avatar",+ "description": "Remove the user's profile picture. A picture managed by the identity provider can't be removed, but an earlier Kaneo upload can.",+ "parameters": [+ {+ "schema": {+ "type": "string",+ "minLength": 1+ },+ "required": true,+ "name": "userId",+ "in": "path"+ }+ ],+ "responses": {+ "200": {+ "description": "Picture removed",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/AdminUserAvatarRemoved"+ }+ }+ }+ },+ "401": {+ "description": "Missing or invalid credentials",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "403": {+ "description": "Not an instance administrator, an API key, or the picture is managed by the identity provider",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "404": {+ "description": "User not found",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ApiError"+ }+ }+ }+ },+ "429": {+ "$ref": "#/components/responses/ApiKeyRateLimited"+ }+ }+ }}},"webhooks": {}diff --git a/tests/api-integration/admin-user-avatar.test.ts b/tests/api-integration/admin-user-avatar.test.tsnew file mode 100644index 000000000..d12e82095--- /dev/null+++ b/tests/api-integration/admin-user-avatar.test.ts@@ -0,0 +1,113 @@+import { randomUUID } from "node:crypto";+import { eq } from "drizzle-orm";+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vite-plus/test";+import db, { schema } from "../../apps/api/src/database";+import { adminWithTarget } from "./helpers/admin/admin-users-api";+import { readAuditLog } from "./helpers/admin/read-audit-log";+import { resetTestDatabase } from "./helpers/database";+import { readErrorBody } from "./helpers/error-body";++const PNG = Buffer.from([+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00,+]).toString("base64");+const PICTURE = "https://id.example.com/tom.png";++let setup: Awaited<ReturnType<typeof adminWithTarget>>;++beforeEach(async () => {+ await resetTestDatabase();+ setup = await adminWithTarget();+});+afterEach(() => vi.unstubAllEnvs());++const avatar = (method: string, body?: unknown) =>+ setup.asAdmin(`/${setup.target.userId}/avatar`, { method, body });+const upload = () => avatar("PUT", { contentType: "image/png", data: PNG });++async function targetImage() {+ const [user] = await db+ .select({ image: schema.userTable.image })+ .from(schema.userTable)+ .where(eq(schema.userTable.id, setup.target.userId));+ return user?.image;+}++async function manageImageByProvider(image: string | null) {+ vi.stubEnv("CUSTOM_OAUTH_MANAGED_PROFILE_FIELDS", "image");+ await db.insert(schema.accountTable).values({+ accountId: `sub-${randomUUID()}`,+ providerId: "custom",+ userId: setup.target.userId,+ });+ await db+ .update(schema.userTable)+ .set({ image })+ .where(eq(schema.userTable.id, setup.target.userId));+}++describe("admin avatar management", () => {+ it("sets and removes another user's avatar, recording each once", async () => {+ const set = await upload();+ expect(set.status, await set.clone().text()).toBe(200);+ const { image } = (await set.json()) as { image: string };+ expect(image).toMatch(/^\/api\/user\/avatar\//);+ expect(await targetImage()).toBe(image);+ const served = await setup.app.request(image);+ expect(served.status).toBe(200);++ const removed = await avatar("DELETE");+ expect(await removed.json()).toEqual({ removed: true });+ expect(await targetImage()).toBeNull();+ expect(await db.select().from(schema.userAvatarTable)).toEqual([]);++ const again = await avatar("DELETE");+ expect(await again.json()).toEqual({ removed: false });++ const rows = await readAuditLog();+ expect(rows.map((row) => row.action)).toEqual([+ "user.avatar_changed",+ "user.avatar_removed",+ ]);+ expect(rows.every((row) => row.targetId === setup.target.userId)).toBe(+ true,+ );+ expect(JSON.stringify(rows)).not.toContain(PNG);+ });++ it("rejects images that are not what they claim", async () => {+ const response = await avatar("PUT", {+ contentType: "image/jpeg",+ data: PNG,+ });+ expect(response.status).toBe(400);+ expect(await targetImage()).toBeNull();+ expect(await readAuditLog()).toEqual([]);+ });++ it("keeps a picture the identity provider manages", async () => {+ await manageImageByProvider(PICTURE);+ const set = await upload();+ expect(set.status).toBe(403);+ expect((await readErrorBody(set)).code).toBe(+ "PROFILE_FIELD_MANAGED_BY_PROVIDER",+ );+ expect((await avatar("DELETE")).status).toBe(403);+ expect(await targetImage()).toBe(PICTURE);+ expect(await readAuditLog()).toEqual([]);+ });++ it("can still withdraw an earlier Kaneo upload when the provider manages pictures", async () => {+ expect((await upload()).status).toBe(200);+ await manageImageByProvider((await targetImage()) ?? null);+ const removed = await avatar("DELETE");+ expect(removed.status).toBe(200);+ expect(await targetImage()).toBeNull();+ });+});diff --git a/tests/api-integration/admin-user-creation.test.ts b/tests/api-integration/admin-user-creation.test.tsnew file mode 100644index 000000000..eb0569882--- /dev/null+++ b/tests/api-integration/admin-user-creation.test.ts@@ -0,0 +1,192 @@+import * as email from "@kaneo/email";+import { eq } from "drizzle-orm";+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vite-plus/test";+import db, { schema } from "../../apps/api/src/database";+import { adminWithTarget } from "./helpers/admin/admin-users-api";+import { readAuditLog } from "./helpers/admin/read-audit-log";+import { resetTestDatabase } from "./helpers/database";+import { readErrorBody } from "./helpers/error-body";++type Created = {+ user: {+ id: string;+ email: string;+ name: string;+ role: string;+ emailVerified: boolean;+ signInMethods: string[];+ lastActiveAt: string | null;+ };+ passwordSetupEmail: string;+};++const newUser = { name: "Nora New", email: "[email protected]", role: "admin" };++let setup: Awaited<ReturnType<typeof adminWithTarget>>;++beforeEach(async () => {+ await resetTestDatabase();+ setup = await adminWithTarget();+ vi.spyOn(email, "isSmtpConfigured").mockReturnValue(true);+ vi.spyOn(email, "sendAccountPasswordEmail").mockResolvedValue({+ success: true,+ });+});+afterEach(() => vi.unstubAllEnvs());++const create = (body: unknown = newUser) =>+ setup.asAdmin("", { method: "POST", body });++async function createdRows() {+ return (await readAuditLog()).filter((row) => row.action === "user.created");+}++describe("POST /api/admin/users", () => {+ it("creates the account without a password and emails a link to set one", async () => {+ const response = await create();+ const text = await response.text();+ expect(response.status, text).toBe(201);+ const { user, passwordSetupEmail } = JSON.parse(text) as Created;+ expect(passwordSetupEmail).toBe("sent");+ expect(user).toMatchObject({+ name: "Nora New",+ email: "[email protected]",+ role: "admin",+ emailVerified: false,+ signInMethods: [],+ lastActiveAt: null,+ });+ expect(+ await db+ .select()+ .from(schema.accountTable)+ .where(eq(schema.accountTable.userId, user.id)),+ ).toEqual([]);++ expect(email.sendAccountPasswordEmail).toHaveBeenCalledOnce();+ const [to, subject, data] = vi.mocked(email.sendAccountPasswordEmail).mock+ .calls[0] as [string, string, { purpose: string; passwordLink: string }];+ expect(to).toBe("[email protected]");+ expect(subject).toBe("Set up your Kaneo account");+ expect(data.purpose).toBe("setup");+ const link = new URL(data.passwordLink);+ const token = link.pathname.split("/").at(-1) as string;+ expect(text).not.toContain(token);++ const [verification] = await db.select().from(schema.verificationTable);+ const lifetime = (verification?.expiresAt.getTime() ?? 0) - Date.now();+ expect(lifetime).toBeGreaterThan(47 * 3_600_000);+ expect(lifetime).toBeLessThanOrEqual(48 * 3_600_000);++ const audit = await createdRows();+ expect(audit).toHaveLength(1);+ expect(audit[0]).toMatchObject({+ actorUserId: setup.admin.userId,+ targetType: "user",+ targetId: user.id,+ targetLabel: "[email protected]",+ metadata: { name: "Nora New", role: "admin", signIn: "password_link" },+ userAgent: "admin-users-test",+ });+ expect(JSON.stringify(audit)).not.toContain(token);++ // The emailed link goes through the regular reset flow.+ const callback = await setup.app.request(`${link.pathname}${link.search}`);+ expect(callback.status).toBe(302);+ const post = (path: string, body: unknown) =>+ setup.app.request(`/api/auth${path}`, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(body),+ });+ const password = "a fresh password 123";+ expect(+ (await post("/reset-password", { token, newPassword: password })).status,+ ).toBe(200);+ expect(+ (await post("/sign-in/email", { email: "[email protected]", password }))+ .status,+ ).toBe(200);+ });++ it("rejects a duplicate email regardless of case", async () => {+ const response = await create({+ ...newUser,+ email: "[email protected]",+ });+ expect(response.status).toBe(409);+ expect((await readErrorBody(response)).code).toBe("USER_ALREADY_EXISTS");+ expect(await createdRows()).toEqual([]);+ expect(email.sendAccountPasswordEmail).not.toHaveBeenCalled();+ });++ it("rejects invalid input", async () => {+ for (const body of [+ { ...newUser, email: "not-an-email" },+ { ...newUser, name: " " },+ { ...newUser, role: "owner" },+ ]) {+ expect((await create(body)).status).toBe(400);+ }+ expect(await createdRows()).toEqual([]);+ });++ it("tells the administrator when email delivery is not configured", async () => {+ vi.mocked(email.isSmtpConfigured).mockReturnValue(false);+ const response = await create();+ expect(response.status).toBe(201);+ expect(((await response.json()) as Created).passwordSetupEmail).toBe(+ "not_configured",+ );+ expect(email.sendAccountPasswordEmail).not.toHaveBeenCalled();+ expect(await db.select().from(schema.verificationTable)).toEqual([]);+ expect(await createdRows()).toHaveLength(1);+ });++ it("reports a failed delivery but keeps the account", async () => {+ vi.mocked(email.sendAccountPasswordEmail).mockRejectedValue(+ new Error("SMTP down"),+ );+ const response = await create();+ expect(response.status).toBe(201);+ expect(((await response.json()) as Created).passwordSetupEmail).toBe(+ "failed",+ );+ expect(await createdRows()).toHaveLength(1);+ });++ it("creates single sign-on accounts when password registration is disabled", async () => {+ vi.stubEnv("DISABLE_PASSWORD_REGISTRATION", "true");+ const response = await create();+ expect(response.status).toBe(201);+ const body = (await response.json()) as Created;+ expect(body.passwordSetupEmail).toBe("not_needed");+ expect(body.user.emailVerified).toBe(true);+ expect(email.sendAccountPasswordEmail).not.toHaveBeenCalled();+ expect((await createdRows())[0]?.metadata).toMatchObject({+ signIn: "single_sign_on",+ });+ });++ it("is not blocked by closed registration", async () => {+ vi.stubEnv("DISABLE_REGISTRATION", "true");+ expect((await create()).status).toBe(201);+ });++ it("rejects disposable addresses on Kaneo Cloud", async () => {+ vi.stubEnv("KANEO_CLOUD", "true");+ const response = await create({ ...newUser, email: "[email protected]" });+ expect(response.status).toBe(400);+ expect((await readErrorBody(response)).code).toBe(+ "DISPOSABLE_EMAIL_NOT_ALLOWED",+ );+ expect(await createdRows()).toEqual([]);+ });+});diff --git a/tests/api-integration/admin-user-credentials.test.ts b/tests/api-integration/admin-user-credentials.test.tsnew file mode 100644index 000000000..8fb02b6e2--- /dev/null+++ b/tests/api-integration/admin-user-credentials.test.ts@@ -0,0 +1,176 @@+import * as email from "@kaneo/email";+import { eq } from "drizzle-orm";+import {+ afterEach,+ beforeEach,+ describe,+ expect,+ it,+ vi,+} from "vite-plus/test";+import db, { schema } from "../../apps/api/src/database";+import { adminWithTarget } from "./helpers/admin/admin-users-api";+import { readAuditLog } from "./helpers/admin/read-audit-log";+import { resetTestDatabase } from "./helpers/database";+import { readErrorBody } from "./helpers/error-body";++let setup: Awaited<ReturnType<typeof adminWithTarget>>;++beforeEach(async () => {+ await resetTestDatabase();+ setup = await adminWithTarget();+ vi.spyOn(email, "isSmtpConfigured").mockReturnValue(true);+ vi.spyOn(email, "sendAccountPasswordEmail").mockResolvedValue({+ success: true,+ });+ vi.spyOn(email, "sendEmailVerificationEmail").mockResolvedValue({+ success: true,+ });+});+afterEach(() => vi.unstubAllEnvs());++const post = (path: string, method = "POST") =>+ setup.asAdmin(`/${setup.target.userId}${path}`, { method });++async function auditRows(action: string) {+ return (await readAuditLog()).filter((row) => row.action === action);+}++async function targetVerified() {+ const [user] = await db+ .select({ emailVerified: schema.userTable.emailVerified })+ .from(schema.userTable)+ .where(eq(schema.userTable.id, setup.target.userId));+ return user?.emailVerified;+}++describe("POST /api/admin/users/{userId}/password-reset-email", () => {+ it("emails a one-hour reset link without returning it", async () => {+ const response = await post("/password-reset-email");+ const text = await response.text();+ expect(response.status, text).toBe(200);+ expect(JSON.parse(text)).toEqual({ sent: true });++ const [to, subject, data] = vi.mocked(email.sendAccountPasswordEmail).mock+ .calls[0] as [string, string, { purpose: string; passwordLink: string }];+ expect(to).toBe("[email protected]");+ expect(subject).toBe("Choose a new Kaneo password");+ expect(data.purpose).toBe("reset");+ const token = new URL(data.passwordLink).pathname.split("/").at(-1);+ expect(text).not.toContain(token);++ const [verification] = await db.select().from(schema.verificationTable);+ const lifetime = (verification?.expiresAt.getTime() ?? 0) - Date.now();+ expect(lifetime).toBeGreaterThan(3_500_000);+ expect(lifetime).toBeLessThanOrEqual(3_600_000);++ const rows = await readAuditLog();+ expect(rows).toHaveLength(1);+ expect(rows[0]).toMatchObject({+ action: "user.password_reset_sent",+ actorUserId: setup.admin.userId,+ targetId: setup.target.userId,+ targetLabel: "[email protected]",+ metadata: null,+ });+ expect(JSON.stringify(rows)).not.toContain(token);+ });++ it("explains why nothing was sent and records nothing", async () => {+ vi.mocked(email.isSmtpConfigured).mockReturnValue(false);+ let response = await post("/password-reset-email");+ expect(response.status).toBe(503);+ expect((await readErrorBody(response)).code).toBe(+ "EMAIL_DELIVERY_NOT_CONFIGURED",+ );++ vi.mocked(email.isSmtpConfigured).mockReturnValue(true);+ vi.mocked(email.sendAccountPasswordEmail).mockRejectedValue(+ new Error("SMTP down"),+ );+ response = await post("/password-reset-email");+ expect(response.status).toBe(502);+ expect((await readErrorBody(response)).code).toBe("EMAIL_DELIVERY_FAILED");++ vi.stubEnv("DISABLE_LOGIN_FORM", "true");+ response = await post("/password-reset-email");+ expect(response.status).toBe(409);+ expect((await readErrorBody(response)).code).toBe(+ "PASSWORD_SIGN_IN_DISABLED",+ );++ expect(await readAuditLog()).toEqual([]);+ });++ it("refuses guest accounts", async () => {+ await db+ .update(schema.userTable)+ .set({ isAnonymous: true })+ .where(eq(schema.userTable.id, setup.target.userId));+ const response = await post("/password-reset-email");+ expect(response.status).toBe(409);+ expect((await readErrorBody(response)).code).toBe("GUEST_ACCOUNT");+ expect(email.sendAccountPasswordEmail).not.toHaveBeenCalled();+ });+});++describe("POST /api/admin/users/{userId}/verification-email", () => {+ it("emails a link that verifies the address", async () => {+ const response = await post("/verification-email");+ const text = await response.text();+ expect(response.status, text).toBe(200);++ const [to, subject, data] = vi.mocked(email.sendEmailVerificationEmail).mock+ .calls[0] as [string, string, { verificationLink: string }];+ expect(to).toBe("[email protected]");+ expect(subject).toBe("Confirm your email address for Kaneo");+ const link = new URL(data.verificationLink);+ expect(text).not.toContain(link.searchParams.get("token"));+ expect(await auditRows("user.verification_sent")).toHaveLength(1);+ expect(await readAuditLog()).toHaveLength(1);++ const visit = await setup.app.request(`${link.pathname}${link.search}`);+ expect(visit.status).toBe(302);+ expect(visit.headers.get("location")).toBe(+ "http://localhost:5173/auth/sign-in",+ );+ expect(await targetVerified()).toBe(true);+ });++ it("refuses an address that is already verified", async () => {+ await db+ .update(schema.userTable)+ .set({ emailVerified: true })+ .where(eq(schema.userTable.id, setup.target.userId));+ const response = await post("/verification-email");+ expect(response.status).toBe(409);+ expect((await readErrorBody(response)).code).toBe("EMAIL_ALREADY_VERIFIED");+ expect(email.sendEmailVerificationEmail).not.toHaveBeenCalled();+ expect(await readAuditLog()).toEqual([]);+ });++ it("does not record an email that was not sent", async () => {+ vi.mocked(email.isSmtpConfigured).mockReturnValue(false);+ expect((await post("/verification-email")).status).toBe(503);+ expect(await readAuditLog()).toEqual([]);+ });+});++describe("PUT /api/admin/users/{userId}/email-verified", () => {+ it("marks the email verified once", async () => {+ expect(await targetVerified()).toBe(false);+ const first = await post("/email-verified", "PUT");+ expect(first.status).toBe(200);+ expect(await first.json()).toEqual({ emailVerified: true });+ expect(await targetVerified()).toBe(true);++ expect((await post("/email-verified", "PUT")).status).toBe(200);+ const rows = await readAuditLog();+ expect(rows).toHaveLength(1);+ expect(rows[0]).toMatchObject({+ action: "user.email_verified",+ targetId: setup.target.userId,+ targetLabel: "[email protected]",+ });+ });+});diff --git a/tests/api-integration/admin-user-lifecycle-access.test.ts b/tests/api-integration/admin-user-lifecycle-access.test.tsnew file mode 100644index 000000000..fdebbb02c--- /dev/null+++ b/tests/api-integration/admin-user-lifecycle-access.test.ts@@ -0,0 +1,66 @@+import { beforeEach, describe, expect, it } from "vite-plus/test";+import { auth } from "../../apps/api/src/auth";+import { readAuditLog } from "./helpers/admin/read-audit-log";+import {+ adminUsersApi,+ adminWithTarget,+} from "./helpers/admin/admin-users-api";+import { resetTestDatabase } from "./helpers/database";++const PNG = Buffer.from([+ 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00,+]).toString("base64");++const endpoints = (userId: string) => [+ {+ path: "",+ method: "POST",+ body: { name: "New", email: "[email protected]", role: "admin" },+ },+ { path: `/${userId}/password-reset-email`, method: "POST" },+ { path: `/${userId}/verification-email`, method: "POST" },+ { path: `/${userId}/email-verified`, method: "PUT" },+ {+ path: `/${userId}/avatar`,+ method: "PUT",+ body: { contentType: "image/png", data: PNG },+ },+ { path: `/${userId}/avatar`, method: "DELETE" },+];++beforeEach(resetTestDatabase);++describe("admin user lifecycle endpoints", () => {+ it("reject anonymous callers, regular users, and administrator API keys", async () => {+ const { app, admin, target } = await adminWithTarget();+ const { key } = await auth.api.createApiKey({+ body: { userId: admin.userId, name: "Lifecycle test" },+ });+ const callers = [+ { headers: {}, status: 401 },+ { headers: { cookie: target.cookies }, status: 403 },+ { headers: { "x-api-key": key }, status: 403 },+ { headers: { authorization: `Bearer ${key}` }, status: 403 },+ ];++ for (const { headers, status } of callers) {+ const request = adminUsersApi(app, headers);+ for (const endpoint of endpoints(target.userId)) {+ const response = await request(endpoint.path, endpoint);+ expect(response.status, `${endpoint.method} ${endpoint.path}`).toBe(+ status,+ );+ }+ }+ expect(await readAuditLog()).toEqual([]);+ });++ it("answer 404 for an unknown user", async () => {+ const { asAdmin } = await adminWithTarget();+ for (const endpoint of endpoints("missing-user").slice(1)) {+ const response = await asAdmin(endpoint.path, endpoint);+ expect(response.status, `${endpoint.method} ${endpoint.path}`).toBe(404);+ }+ expect(await readAuditLog()).toEqual([]);+ });+});diff --git a/tests/api-integration/admin-user-listing.test.ts b/tests/api-integration/admin-user-listing.test.tsindex 3675db860..56de82b18 100644--- a/tests/api-integration/admin-user-listing.test.ts+++ b/tests/api-integration/admin-user-listing.test.ts@@ -187,4 +187,94 @@ describe("API integration: admin user listing", () => {expect((await listUsers(app, { limit: "101" })).status).toBe(400);expect((await listUsers(app, { limit: "abc" })).status).toBe(400);});++ it("filters by status, role, and email verification", async () => {+ const admin = await createUser({+ name: "Instance Admin",+ email: "[email protected]",+ role: "user,admin",+ });+ const banned = await createUser({+ name: "Banned",+ email: "[email protected]",+ banned: true,+ });+ const unverified = await createUser({+ name: "Unverified",+ email: "[email protected]",+ emailVerified: false,+ role: null,+ });+ mockAuthenticatedSession(admin);+ const { app } = createApp();+ const ids = async (query: Record<string, string>) => {+ const response = await listUsers(app, query);+ expect(response.status).toBe(200);+ const body = (await response.json()) as AdminUserList;+ expect(body.total).toBe(body.users.length);+ return body.users.map((user) => user.id).sort();+ };++ expect(await ids({ status: "deactivated" })).toEqual([banned.id]);+ expect(await ids({ status: "active" })).toEqual(+ [admin.id, unverified.id].sort(),+ );+ expect(await ids({ role: "admin" })).toEqual([admin.id]);+ expect(await ids({ role: "user" })).toEqual(+ [banned.id, unverified.id].sort(),+ );+ expect(await ids({ emailVerified: "false" })).toEqual([unverified.id]);+ expect(+ await ids({ emailVerified: "true", status: "active", role: "user" }),+ ).toEqual([]);+ expect((await listUsers(app, { status: "gone" })).status).toBe(400);+ expect((await listUsers(app, { emailVerified: "yes" })).status).toBe(400);+ });++ it("reports last session activity and linked sign-in methods", async () => {+ const admin = await createUser({+ name: "Instance Admin",+ email: "[email protected]",+ role: "admin",+ });+ const member = await createUser({+ name: "Member",+ email: "[email protected]",+ });+ const now = Date.now();+ for (const [index, updatedAt] of [+ new Date(now - 3_600_000),+ new Date(now - 60_000),+ ].entries()) {+ await db.insert(schema.sessionTable).values({+ id: `session-${index}`,+ token: `token-${index}`,+ userId: member.id,+ expiresAt: new Date(now + 3_600_000),+ updatedAt,+ });+ }+ for (const providerId of ["github", "credential", "github"]) {+ await db.insert(schema.accountTable).values({+ accountId: randomUUID(),+ providerId,+ userId: member.id,+ });+ }+ mockAuthenticatedSession(admin);+ const { app } = createApp();++ const body = (await (await listUsers(app)).json()) as {+ users: {+ id: string;+ lastActiveAt: string | null;+ signInMethods: string[];+ }[];+ };+ const listed = body.users.find((user) => user.id === member.id);+ expect(listed?.signInMethods).toEqual(["credential", "github"]);+ expect(listed?.lastActiveAt).toBe(new Date(now - 60_000).toISOString());+ const self = body.users.find((user) => user.id === admin.id);+ expect(self).toMatchObject({ lastActiveAt: null, signInMethods: [] });+ });});diff --git a/tests/api-integration/helpers/admin/admin-users-api.ts b/tests/api-integration/helpers/admin/admin-users-api.tsnew file mode 100644index 000000000..439a979ef--- /dev/null+++ b/tests/api-integration/helpers/admin/admin-users-api.ts@@ -0,0 +1,40 @@+import { createApp } from "../../../../apps/api/src/index";+import { signUpWithSession } from "../auth-session";++type App = ReturnType<typeof createApp>["app"];++/** Requests to `/api/admin/users...` with the given headers. */+export function adminUsersApi(app: App, headers: Record<string, string>) {+ return (path: string, init: { method?: string; body?: unknown } = {}) =>+ app.request(`/api/admin/users${path}`, {+ method: init.method ?? "GET",+ headers: {+ "content-type": "application/json",+ origin: "http://localhost:5173",+ "user-agent": "admin-users-test",+ ...headers,+ },+ ...(init.body === undefined ? {} : { body: JSON.stringify(init.body) }),+ });+}++/** A signed-in instance administrator and a regular user to act on. */+export async function adminWithTarget() {+ const { app } = createApp();+ const admin = await signUpWithSession(app, {+ email: "[email protected]",+ name: "Ada Admin",+ role: "admin",+ });+ const target = await signUpWithSession(app, {+ email: "[email protected]",+ name: "Tom Target",+ role: "user",+ });+ return {+ app,+ admin,+ target,+ asAdmin: adminUsersApi(app, { cookie: admin.cookies }),+ };+}diff --git a/tests/api-integration/mocks/email.ts b/tests/api-integration/mocks/email.tsindex d6dfae6c7..3aaad14ea 100644--- a/tests/api-integration/mocks/email.ts+++ b/tests/api-integration/mocks/email.ts@@ -37,3 +37,19 @@ export async function sendPasswordResetEmail(): Promise<void> {return undefined;}++export async function sendAccountPasswordEmail(+ _to: string,+ _subject: string,+ _data: unknown,+): Promise<EmailResult> {+ return { success: true };+}++export async function sendEmailVerificationEmail(+ _to: string,+ _subject: string,+ _data: unknown,+): Promise<EmailResult> {+ return { success: true };+}