Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

8.8 KB
Raw Blame
/**
 * Admin user backend: user list / create / reset password / delete.
 *
 * - Create: username is the user_id (^[a-z][a-z0-9_-]{1,31}$); admin sets the initial
 *   password, flagged with password_is_initial; a default Project `proj-<username>` is
 *   auto-created, rolling back the user row on failure.
 * - Reset password: also flags the password as initial and clears all of the user's
 *   login sessions (forcing re-login).
 * - Delete: the built-in admin cannot be deleted; Projects owned by the user are
 *   deleted along with it (including data directories), with sessions/memberships/UI
 *   preferences cascade-deleted via foreign keys.
 *
 * Both of those end sessions, so both go through `signOutEverywhere`: dropping the rows
 * alone leaves the connections those rows authorised still open.
 */
import type { UserInfo } from "../api/types.js";
import { HttpError } from "../http/errors.js";
import { ADMIN_USER_ID, MIN_PASSWORD_LENGTH, toUserInfo } from "../auth/service.js";
import type { PasswordHasher } from "../auth/password.js";
import type { UserRow } from "../db/repos/users.js";
import { SEMANTIC_ID_RULE, USERNAME_PATTERN } from "./ids.js";
import { Component, Use } from "@adelie/core/kernel";
import type { Clock } from "../hmr/capabilities.js";
import type { LiveStreams } from "../auth/live-streams.js";
import type { SessionIndex } from "../mechanisms/sessions.js";
import type { Admin, AuthSessions, Users } from "../mechanisms/identity.js";
import type { UsageQueries } from "../mechanisms/observability.js";
import type { ProjectLifecycle, Projects } from "../mechanisms/projects.js";

@Component()
export class AdminService implements Admin {
  @Use() private readonly users!: Users;
  @Use() private readonly authSessions!: AuthSessions;
  @Use() private readonly liveStreams!: LiveStreams;
  @Use() private readonly projects!: Projects;
  @Use() private readonly sessions!: SessionIndex;
  @Use() private readonly usage!: UsageQueries;
  @Use() private readonly projectService!: ProjectLifecycle;
  @Use() private readonly clock!: Clock;
  @Use() private readonly hasher!: PasswordHasher;

  /**
   * Every account, for the admin user backend, each with the last sign-in its row carries and
   * the lifetime cost of the Projects it owns. The avatar is dropped on the way out: a stored
   * avatar is a data URL of up to 128 KiB and this list is unpaged, so carrying one per account
   * would answer a table that only shows the nickname with megabytes.
   *
   * The cost is summed per Project because a Project is what carries the price a Request was
   * billed at, and every record contributes the cost fixed when it was written — the one figure
   * the cost center's "cumulative" card shows, extended over everything the account owns.
   * `costUnpriced` travels with it: a Model this deployment had no price for makes the sum a
   * lower bound, and a table that presented it as exact would overstate its own accuracy.
   */
  async listUsers(): Promise<UserInfo[]> {
    const out: UserInfo[] = [];
    for (const row of this.users.list()) {
      const { avatar: _avatar, ...info } = toUserInfo(row);
      const owned = this.projects.listByOwner(row.userId).map((p) => p.projectId);
      out.push({
        ...info,
        ...(await this.ownedProjectsCost(owned)),
        ...this.lastSession(owned),
      });
    }
    return out;
  }

  /** One account's owned Projects, priced and summed; `totalCostUsd` is omitted while nothing could be priced. */
  private async ownedProjectsCost(
    projectIds: readonly string[],
  ): Promise<Pick<UserInfo, "totalCostUsd" | "costUnpriced">> {
    let cost: number | null = null;
    let unpriced = false;
    for (const projectId of projectIds) {
      const figure = await this.usage.lifetimeCost(projectId);
      if (figure.cost !== null) cost = (cost ?? 0) + figure.cost;
      unpriced = unpriced || figure.unpriced;
    }
    return {
      ...(cost !== null ? { totalCostUsd: cost } : {}),
      ...(unpriced ? { costUnpriced: true } : {}),
    };
  }

  /**
   * The account's most recent Session across the Projects it owns, as a time plus (when the
   * Session already has one) its title. Ordered by activity, the same figure the sidebar calls
   * 「最近更新」: the question the column answers is "which conversation did this account touch
   * last", so the newest stamp is the one to show, not the newest creation.
   *
   * Sessions are listed as they are stored — no filtering by archive state or by who opened
   * one, and subagent Sessions are rows here like anywhere else. Every other list in the
   * product draws the same set, and an account's own conversation is what an admin is looking
   * at, not a curated subset of it.
   */
  private lastSession(
    projectIds: readonly string[],
  ): Pick<UserInfo, "lastSessionAt" | "lastSessionTitle"> {
    const row = this.sessions.latestByProjects(projectIds);
    if (!row) return {};
    return {
      lastSessionAt: row.lastActiveAt,
      ...(row.title !== null && row.title !== "" ? { lastSessionTitle: row.title } : {}),
    };
  }

  async createUser(userId: string, password: string): Promise<UserInfo> {
    if (!USERNAME_PATTERN.test(userId)) {
      throw new HttpError(
        400,
        "invalid_user_id",
        `Username must be 2–32 characters: ${SEMANTIC_ID_RULE}.`,
      );
    }
    if (password.length < MIN_PASSWORD_LENGTH) {
      throw new HttpError(400, "invalid_password", "Password must be at least 8 characters.");
    }
    if (this.users.findById(userId)) {
      throw new HttpError(409, "user_exists", `User already exists: ${userId}.`);
    }
    const user: UserRow = {
      userId,
      passwordHash: await this.hasher.hash(password),
      isAdmin: false,
      passwordIsInitial: true,
      displayName: null,
      avatar: null,
      lastLoginAt: null,
      createdAt: this.clock.now().toISOString(),
    };
    this.users.insert(user);
    try {
      await this.projectService.provisionInitialProject(user, false);
    } catch (err) {
      // Compensation: roll back the user row if default Project creation fails (e.g. proj-<username> already taken).
      this.users.delete(user.userId);
      throw err;
    }
    return toUserInfo(user);
  }

  /**
   * Reset a user's password and clear all their sessions (prompts a password change on next
   * login). Only an admin reaches this route, so `userId === admin` is the admin resetting
   * ITSELF: it chose a KNOWN password, which is a claimed state — not the unclaimed one the
   * first-login link exists for — so the initial flag stays off and no link is re-opened.
   * Every other user gets the flag, to be prompted to change the password their admin picked.
   */
  async resetPassword(userId: string, password: string): Promise<void> {
    if (!this.users.findById(userId)) {
      throw new HttpError(404, "user_not_found", `User does not exist: ${userId}.`);
    }
    if (password.length < MIN_PASSWORD_LENGTH) {
      throw new HttpError(400, "invalid_password", "Password must be at least 8 characters.");
    }
    const isSelfAdminReset = userId === ADMIN_USER_ID;
    this.users.updatePassword(userId, await this.hasher.hash(password), !isSelfAdminReset);
    this.signOutEverywhere(userId);
  }

  /**
   * Sign a user out of every window: the session rows go, and so does every SSE stream
   * those sessions authorised. The two belong together — a stream is authorised once, when
   * it connects, so dropping the rows on their own leaves the window streaming happily
   * until its reader happens to make a request. Anything that revokes a user's sessions
   * calls this rather than the repo directly. Forgetting it is not fatal: each stream
   * re-checks its own session on the next heartbeat (http/sse.ts), which costs the window
   * one beat instead of ending it at once.
   */
  private signOutEverywhere(userId: string): void {
    this.authSessions.deleteByUser(userId);
    this.liveStreams.endForUser(userId);
  }

  /** Delete user: the built-in admin cannot be deleted; owned Projects (including data directories) are deleted along with it. */
  async deleteUser(userId: string): Promise<void> {
    const target = this.users.findById(userId);
    if (!target) {
      throw new HttpError(404, "user_not_found", `User does not exist: ${userId}.`);
    }
    if (target.isAdmin) {
      throw new HttpError(409, "cannot_delete_admin", "The built-in admin cannot be deleted.");
    }
    for (const project of this.projects.listByOwner(userId)) {
      await this.projectService.destroyProject(project.projectId);
    }
    this.users.delete(userId); // project_members / ui_prefs cascade-deleted
    // The session rows went with the user row (ON DELETE CASCADE), so this is about the
    // connections they authorised: a window left open on a deleted account would go on
    // streaming until it tried to fetch something.
    this.signOutEverywhere(userId);
  }
}