VNOX-Web/src/api.ts

90 lines
2.5 KiB
TypeScript

export interface User {
user_id: string;
handle: string;
display_name: string;
avatar_url?: string | null;
}
export type Session =
| { authenticated: false }
| { authenticated: true; user: User; csrf_token: string };
export interface HubInfo {
capabilities: { github_auth: string };
}
export interface RequestOptions {
signal?: AbortSignal;
method?: "GET" | "POST";
csrf?: string;
fetcher?: (input: string, options: RequestInit) => Promise<Response>;
}
export class ApiError extends Error {
readonly status: number;
constructor(status: number, code: string) {
super(code);
this.name = "ApiError";
this.status = status;
}
}
export async function request(
path: string,
{ signal, method = "GET", csrf, fetcher = fetch }: RequestOptions = {},
): Promise<unknown> {
if (!path.startsWith("/v1/"))
throw new TypeError("Only same-origin VNOX API paths are allowed");
const response = await fetcher(path, {
method,
signal,
credentials: "same-origin",
cache: "no-store",
headers: {
Accept: "application/json",
...(csrf ? { "X-CSRF-Token": csrf } : {}),
},
});
if (!response.ok) throw new ApiError(response.status, "request_failed");
if (response.status === 204) return null;
return response.json();
}
function record(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}
export function isSession(value: unknown): value is Session {
if (!record(value)) return false;
if (value.authenticated === false) return true;
if (
value.authenticated !== true ||
typeof value.csrf_token !== "string" ||
value.csrf_token.length === 0 ||
!record(value.user)
)
return false;
return (
typeof value.user.user_id === "string" &&
typeof value.user.handle === "string" &&
typeof value.user.display_name === "string" &&
(value.user.avatar_url === undefined ||
value.user.avatar_url === null ||
typeof value.user.avatar_url === "string")
);
}
export function isInfo(value: unknown): value is HubInfo {
return (
record(value) &&
record(value.capabilities) &&
typeof value.capabilities.github_auth === "string"
);
}
export function safeAvatar(value: unknown): string | null {
if (typeof value !== "string") return null;
try {
const url = new URL(value);
return url.protocol === "https:" &&
url.hostname === "avatars.githubusercontent.com" &&
!url.username &&
!url.password &&
!url.port
? url.href
: null;
} catch {
return null;
}
}