clove/pkviewer
web/src/lib/server/api.ts
/* web/src/lib/server/api.ts */
import { env } from "$env/dynamic/private";
import { getRequestEvent } from "$app/server";
import type { CreditSection, PageModel, PublicBadge } from "@pkviewer/shared";
import { site } from "$lib/config.ts";
import type { DiscoveredSystem } from "$lib/types.ts";
/**
* The web tier's only route to data.
*
* The browser never talks to the API: INTERNAL_API_ORIGIN stays internal, and
* the session cookie is forwarded from the load or remote function making the
* call. That keeps the __Host- cookie pinned to one host.
*/
export function apiOrigin(): string {
return (env["INTERNAL_API_ORIGIN"] || "http://127.0.0.1:3001").replace(/\/+$/, "");
}
// ------------------------------------------------------------------ public
export type PublicPage = PageModel & { canonicalPath: string };
export type FetchOutcome<T> =
| { ok: true; value: T }
| { ok: false; status: number; reason: string };
async function getJson<T>(path: string): Promise<FetchOutcome<T>> {
let res: Response;
try {
// Public pages re-render per request; the API holds the cache.
res = await fetch(`${apiOrigin()}${path}`, {
headers: {
accept: "application/json",
},
});
} catch {
return {
ok: false,
status: 503,
reason: "api_unreachable",
};
}
if (!res.ok) {
const body = (await res.json().catch(() => null)) as { error?: string } | null;
return {
ok: false,
status: res.status,
reason: body?.error ?? "error",
};
}
return {
ok: true,
value: (await res.json()) as T,
};
}
export function getSystemPage(ref: string): Promise<FetchOutcome<PublicPage>> {
return getJson<PublicPage>(`/public/systems/${encodeURIComponent(ref)}`);
}
export function getMemberPage(ref: string, memberRef: string): Promise<FetchOutcome<PublicPage>> {
return getJson<PublicPage>(
`/public/systems/${encodeURIComponent(ref)}/members/${encodeURIComponent(memberRef)}`,
);
}
/** The credits page. Platform-owned content: no subject, no session. */
export function getCredits(): Promise<FetchOutcome<{ sections: CreditSection[] }>> {
return getJson<{ sections: CreditSection[] }>("/public/credits");
}
/** The badge glossary, so every badge on a page can link to what it means. */
export function getBadgeCatalogue(): Promise<FetchOutcome<{ badges: PublicBadge[] }>> {
return getJson<{ badges: PublicBadge[] }>("/public/badges");
}
// ------------------------------------------------------------------ manage
export type ApiResult<T> =
| { ok: true; value: T }
| { ok: false; status: number; error: string; detail?: unknown };
async function call<T>(
path: string,
init: { method?: string; body?: unknown } = {},
): Promise<ApiResult<T>> {
const cookieHeader = getRequestEvent().request.headers.get("cookie") ?? "";
const headers: Record<string, string> = {
accept: "application/json",
cookie: cookieHeader,
// The API rejects state-changing requests without a recognised Origin.
origin: site.publicOrigin,
};
if (init.body !== undefined) headers["content-type"] = "application/json";
let res: Response;
try {
res = await fetch(`${apiOrigin()}${path}`, {
method: init.method ?? "GET",
headers,
...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}),
});
} catch {
return {
ok: false,
status: 503,
error: "api_unreachable",
};
}
const payload = (await res.json().catch(() => null)) as Record<string, unknown> | null;
if (!res.ok) {
return {
ok: false,
status: res.status,
error: typeof payload?.["error"] === "string" ? (payload["error"] as string) : "error",
detail: payload?.["rejected"] ?? payload?.["errors"],
};
}
return {
ok: true,
value: (payload ?? {}) as T,
};
}
export const manageApi = {
get: <T>(path: string) => call<T>(path),
put: <T>(path: string, body: unknown) => call<T>(path, { method: "PUT", body }),
post: <T>(path: string, body: unknown) => call<T>(path, { method: "POST", body }),
del: <T>(path: string) => call<T>(path, { method: "DELETE" }),
};
/** One path segment, so a caller-supplied id can never walk the API's routes. */
export function seg(value: string | number): string {
return encodeURIComponent(String(value));
}
/**
* Whether the signed-in account administers pkviewer.
*
* Used only to decide whether to show a link. Every admin route re-checks it
* on the API, because a hidden link is not a permission boundary.
*/
export async function isPlatformAdmin(): Promise<boolean> {
const result = await manageApi.get<{ admin: boolean }>("/admin/whoami");
return result.ok && result.value.admin === true;
}
/** Whether the caller has a session at all. */
export async function isAuthenticated(): Promise<boolean> {
const result = await call<{ authenticated: boolean }>("/auth/me");
return result.ok && result.value.authenticated === true;
}
// ---------------------------------------------------------------- claiming
/**
* Systems linked to the signed-in Discord account.
*
* The Discord identities are read from the session by the API, never sent from
* here (invariant S1). Shared by the claim page's load and its remote command.
*/
export async function discoverSystems(): Promise<
{ ok: true; systems: DiscoveredSystem[] } | { ok: false; error: string }
> {
const result = await manageApi.post<{ systems: DiscoveredSystem[] }>("/claims/discover", {});
if (!result.ok) {
return {
ok: false,
error:
result.error === "unauthenticated"
? "Your session has expired. Sign in again."
: "Could not reach PluralKit just now. Try again shortly.",
};
}
return {
ok: true,
systems: result.value.systems,
};
}