Dough Git

clove/pkviewer

web/src/lib/manage.remote.ts

back to web/src/lib

/* web/src/lib/manage.remote.ts */
import { command } from "$app/server";
import type { CssIssue } from "@pkviewer/shared";
import { discoverSystems as discover, manageApi, seg } from "$lib/server/api.ts";
import type { ActionResult, EditableLink, SlugScope } from "$lib/types.ts";

/**
 * Remote commands for the management UI.
 *
 * Thin: they forward to the API, which re-validates everything and re-checks
 * the grant. The client is never trusted to decide what it may manage, and
 * these do not decide it either. Ids go through seg() so none can walk routes.
 */

function messageFor(error: string, status: number): string {
  switch (error) {
    case "unauthenticated":
      return "Your session has expired. Sign in again.";
    case "not_found":
      return "You do not have access to this system.";
    case "validation_failed":
      return "Some settings were not accepted. Check the values and try again.";
    case "api_unreachable":
      return "Could not reach pkviewer. Check your connection and try again.";
    default:
      return status >= 500 ? "Something went wrong saving. Please try again." : "Could not save.";
  }
}

function result(response: { ok: true } | { ok: false; error: string; status: number }): ActionResult {
  return response.ok
    ? { ok: true }
    : { ok: false, error: messageFor(response.error, response.status) };
}

// ------------------------------------------------------------ appearance

export const saveSystemTheme = command(
  "unchecked",
  async (input: { systemId: string; tokens: Record<string, string | null> }) =>
    result(await manageApi.put(`/manage/systems/${seg(input.systemId)}/theme`, { tokens: input.tokens })),
);

export const saveSystemComposition = command(
  "unchecked",
  async (input: { systemId: string; composition: Record<string, string> }) =>
    result(
      await manageApi.put(`/manage/systems/${seg(input.systemId)}/theme`, {
        composition: input.composition,
      }),
    ),
);

export const saveMemberTheme = command(
  "unchecked",
  async (input: { systemId: string; memberRef: string; tokens: Record<string, string | null> }) =>
    result(
      await manageApi.put(
        `/manage/systems/${seg(input.systemId)}/members/${seg(input.memberRef)}/theme`,
        { tokens: input.tokens },
      ),
    ),
);

export const saveSystemSocials = command(
  "unchecked",
  async (input: { systemId: string; links: EditableLink[] }) =>
    result(await manageApi.put(`/manage/systems/${seg(input.systemId)}/socials`, { links: input.links })),
);

export const saveMemberSocials = command(
  "unchecked",
  async (input: { systemId: string; memberRef: string; links: EditableLink[] }) =>
    result(
      await manageApi.put(
        `/manage/systems/${seg(input.systemId)}/members/${seg(input.memberRef)}/socials`,
        { links: input.links },
      ),
    ),
);

// ------------------------------------------------------------- addresses

// All validation and the reservation lifecycle live in the API; these only translate its answers

export const checkSlug = command(
  "unchecked",
  async (input: {
    scope: SlugScope;
    subjectId: string;
    systemId: string;
    slug: string;
  }): Promise<{ available: boolean; message?: string; availableAt?: number }> => {
    const params = new URLSearchParams({
      scope: input.scope,
      subjectId: input.subjectId,
      slug: input.slug,
      systemId: input.systemId,
    });
    const response = await manageApi.get<{
      available: boolean;
      reason?: string;
      until?: number;
      message?: string;
    }>(`/manage/slugs/check?${params.toString()}`);

    if (!response.ok) return { available: false, message: "Could not check that address." };
    const value = response.value;
    if (value.available) return { available: true };
    return {
      available: false,
      ...(value.message ? { message: value.message } : {}),
      ...(value.until ? { availableAt: value.until } : {}),
    };
  },
);

export type ClaimSlugResult = {
  ok: boolean;
  error?: string;
  slug?: string;
  previousSlug?: string | null;
  warnings?: Array<{ code: string; memberHid?: string }>;
};

export const claimSlug = command(
  "unchecked",
  async (input: { scope: SlugScope; subjectId: string; slug: string }): Promise<ClaimSlugResult> => {
    const response = await manageApi.post<{
      slug: string;
      previousSlug: string | null;
      warnings: Array<{ code: string; memberHid?: string }>;
    }>("/manage/slugs/claim", input);

    if (!response.ok) {
      // A held address never names who holds it
      const message =
        response.error === "taken"
          ? "That address is already in use."
          : response.error === "reserved"
            ? "That address is held for someone else at the moment."
            : response.error === "conflict"
              ? "Someone claimed that address just now. Try another."
              : response.error === "invalid"
                ? "That address is not allowed."
                : response.error === "forbidden" || response.error === "not_found"
                  ? "You do not have access to change this address."
                  : "Could not set that address.";
      return { ok: false, error: message };
    }

    return {
      ok: true,
      slug: response.value.slug,
      previousSlug: response.value.previousSlug,
      warnings: response.value.warnings,
    };
  },
);

export const releaseSlug = command(
  "unchecked",
  async (input: {
    scope: SlugScope;
    subjectId: string;
  }): Promise<{ ok: boolean; error?: string; reservedUntil?: number | null }> => {
    const response = await manageApi.post<{ released: string; reservedUntil: number | null }>(
      "/manage/slugs/release",
      {
        scope: input.scope,
        subjectId: input.subjectId,
        confirm: true,
      },
    );
    if (!response.ok) {
      return {
        ok: false,
        error:
          response.error === "no_slug"
            ? "There is no address to release."
            : "Could not release that address.",
      };
    }
    return { ok: true, reservedUntil: response.value.reservedUntil };
  },
);

// -------------------------------------------------------------- claiming

// Two routes, Discord link then description code. Neither needs a PluralKit token.

function claimError(error: string): string {
  switch (error) {
    case "already_claimed":
      return "That system is already managed on pkviewer. If it should be yours, get in touch.";
    case "not_verified":
      return "pkviewer could not confirm that system belongs to you.";
    case "not_found":
      return "PluralKit does not have a system with that ID.";
    case "upstream_unavailable":
      return "PluralKit could not be reached. Try again shortly.";
    default:
      return "That did not work. Try again.";
  }
}

export const discoverSystems = command(discover);

export const claimViaDiscord = command(
  "unchecked",
  async (systemRef: string): Promise<{ ok: true; systemId: string } | { ok: false; error: string }> => {
    const response = await manageApi.post<{ systemId: string }>("/claims/discord-link", { systemRef });
    if (!response.ok) return { ok: false, error: claimError(response.error) };
    return { ok: true, systemId: response.value.systemId };
  },
);

export const startChallenge = command(
  "unchecked",
  async (
    systemRef: string,
  ): Promise<
    { ok: true; challengeId: string; nonce: string; systemHid: string } | { ok: false; error: string }
  > => {
    const response = await manageApi.post<{ challengeId: string; nonce: string; systemHid: string }>(
      "/claims/challenge",
      { systemRef },
    );
    if (!response.ok) return { ok: false, error: claimError(response.error) };
    return { ok: true, ...response.value };
  },
);

export const verifyChallenge = command(
  "unchecked",
  async (challengeId: string): Promise<{ ok: true; systemId: string } | { ok: false; error: string }> => {
    const response = await manageApi.post<{ systemId: string }>("/claims/challenge/verify", {
      challengeId,
    });
    if (!response.ok) {
      const message =
        response.error === "not_verified"
          ? "The code is not in the system description yet. Save it in PluralKit, then check again."
          : response.error === "description_unavailable"
            ? "That system's description is not public, so pkviewer cannot read the code. Make it public briefly, or claim from the linked Discord account instead."
            : response.error === "challenge_expired"
              ? "That code expired. Start again for a new one."
              : response.error === "too_many_attempts"
                ? "Too many checks. Start again for a new code."
                : claimError(response.error);
      return { ok: false, error: message };
    }
    return { ok: true, systemId: response.value.systemId };
  },
);

// ---------------------------------------------------------------- badges

// Granting is an admin power; deciding whether it shows on your own page is not
export const respondToBadge = command(
  "unchecked",
  async (input: {
    systemId: string;
    badgeId: string;
    action: "accept" | "decline" | "hide" | "show";
  }) =>
    result(
      await manageApi.post(`/manage/systems/${seg(input.systemId)}/badges/${seg(input.badgeId)}`, {
        action: input.action,
      }),
    ),
);

// ------------------------------------------------------------------- css

export type CssSaveResult = ActionResult & {
  issues?: CssIssue[];
  kept?: number;
};

// The API answers with what it kept and dropped, so the editor reports the truth
export const saveCss = command(
  "unchecked",
  async (input: { systemId: string; memberRef?: string; css: string }): Promise<CssSaveResult> => {
    const path = input.memberRef
      ? `/manage/systems/${seg(input.systemId)}/members/${seg(input.memberRef)}/css`
      : `/manage/systems/${seg(input.systemId)}/css`;
    const response = await manageApi.put<{ issues?: CssIssue[]; kept?: number }>(path, {
      css: input.css,
    });
    if (!response.ok) return { ok: false, error: messageFor(response.error, response.status) };
    return {
      ok: true,
      issues: response.value.issues ?? [],
      kept: response.value.kept ?? 0,
    };
  },
);