VNOX-Web/src/api.ts
loki5512344 a4cae66336
feat(web): sign in by emailed code on the account page
Adds the email form (address, code, resend timer, aria-live status) shown only when
/v1/info reports email_auth enabled, RU/EN strings, privacy policy update, API
helpers, tests and browser QA with a mocked Hub.
2026-10-24 17:49:41 +02:00

134 lines
4 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; email_auth?: string };
}
export interface RequestOptions {
signal?: AbortSignal;
method?: "GET" | "POST";
csrf?: string;
/** JSON request body; only sent when given. */
body?: unknown;
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, body, 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 } : {}),
...(body === undefined ? {} : { "Content-Type": "application/json" }),
},
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
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" &&
(value.capabilities.email_auth === undefined ||
typeof value.capabilities.email_auth === "string")
);
}
/** Result of asking Hub to mail a sign-in code. */
export interface CodeRequest {
resendAfter: number;
}
/** Asks Hub to email a one-time code. Resolves with a bounded resend delay in seconds. */
export async function requestEmailCode(
email: string,
lang: "ru" | "en",
options: Pick<RequestOptions, "signal" | "fetcher"> = {},
): Promise<CodeRequest> {
const value = await request("/v1/auth/email/start", {
...options,
method: "POST",
body: { email, lang },
});
const delay = record(value) ? value.resend_after : undefined;
return {
resendAfter:
typeof delay === "number" && delay >= 1 && delay <= 3600
? Math.ceil(delay)
: 60,
};
}
/** Redeems the code. Resolves only with an authenticated session. */
export async function verifyEmailCode(
email: string,
code: string,
options: Pick<RequestOptions, "signal" | "fetcher"> = {},
): Promise<Session> {
const value = await request("/v1/auth/email/verify", {
...options,
method: "POST",
body: { email, code },
});
if (!isSession(value) || !value.authenticated)
throw new Error("invalid_session");
return value;
}
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;
}
}