185 lines
6.4 KiB
TypeScript
185 lines
6.4 KiB
TypeScript
// This Source Code Form is subject to the terms of the Mozilla Public
|
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
|
|
// The one typed API client (handoff §0, §10, §11). It owns the base path, the UI header (CSRF),
|
|
// redirect: "manual" (sign-out detection), Idempotency-Keys, the error envelope, the server
|
|
// clock offset, rate-limit and in-progress retries, and lost-contact detection. It decides
|
|
// nothing about the data.
|
|
|
|
import type { ErrorBody, ErrorEnvelope } from "./types";
|
|
|
|
export const BASE = "/api/v1";
|
|
|
|
/** A refusal from control, with its envelope. */
|
|
export class ApiError extends Error {
|
|
constructor(
|
|
public status: number,
|
|
public body: ErrorBody,
|
|
public errors: ErrorBody[],
|
|
public requestId: string,
|
|
) {
|
|
super(body.message);
|
|
}
|
|
get code(): string {
|
|
return this.body.code;
|
|
}
|
|
}
|
|
|
|
/** Authelia's portal redirect, or a 401 without Ianitor's envelope. */
|
|
export class SignedOut extends Error {}
|
|
|
|
/** No answer (network, or a proxy error without an envelope). */
|
|
export class LostContact extends Error {}
|
|
|
|
type Listener = () => void;
|
|
|
|
export interface ClientEvents {
|
|
onSignedOut?: Listener;
|
|
onContact?: (ok: boolean) => void;
|
|
onServerTime?: (offsetMs: number) => void;
|
|
}
|
|
|
|
let events: ClientEvents = {};
|
|
export function setClientEvents(e: ClientEvents): void {
|
|
events = e;
|
|
}
|
|
|
|
/** A key for one click; reused by every retry of that click (§11.3). */
|
|
export function newKey(): string {
|
|
if (typeof crypto !== "undefined" && "randomUUID" in crypto) return crypto.randomUUID();
|
|
return Math.random().toString(36).slice(2) + Date.now().toString(36);
|
|
}
|
|
|
|
export interface CallOptions {
|
|
idem?: string;
|
|
etag?: string;
|
|
/** Do not count a failure as lost contact (engine switch, §9.2). */
|
|
quiet?: boolean;
|
|
keepalive?: boolean;
|
|
}
|
|
|
|
export interface Answer<T> {
|
|
status: number;
|
|
data: T | null;
|
|
etag: string | null;
|
|
}
|
|
|
|
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
|
|
function envelope(v: unknown): v is ErrorEnvelope {
|
|
return typeof v === "object" && v !== null && "error" in v && typeof (v as ErrorEnvelope).error === "object";
|
|
}
|
|
|
|
export async function call<T>(
|
|
method: string,
|
|
path: string,
|
|
body?: unknown,
|
|
opts: CallOptions = {},
|
|
): Promise<Answer<T>> {
|
|
let rateRetried = false;
|
|
for (let attempt = 0; attempt < 12; attempt++) {
|
|
const headers: Record<string, string> = { "X-Ianitor-UI": "1", Accept: "application/json" };
|
|
if (body !== undefined) headers["Content-Type"] = "application/json";
|
|
if (opts.idem) headers["Idempotency-Key"] = opts.idem;
|
|
if (opts.etag) headers["If-None-Match"] = opts.etag;
|
|
let res: Response;
|
|
try {
|
|
res = await fetch(BASE + path, {
|
|
method,
|
|
headers,
|
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
redirect: "manual",
|
|
credentials: "same-origin",
|
|
keepalive: opts.keepalive,
|
|
});
|
|
} catch {
|
|
if (!opts.quiet) events.onContact?.(false);
|
|
throw new LostContact("no answer");
|
|
}
|
|
if (res.type === "opaqueredirect" || (res.status >= 300 && res.status < 400 && res.status !== 304)) {
|
|
events.onSignedOut?.();
|
|
throw new SignedOut("signed out");
|
|
}
|
|
if (res.status === 304) {
|
|
events.onContact?.(true);
|
|
return { status: 304, data: null, etag: opts.etag ?? null };
|
|
}
|
|
let json: unknown = null;
|
|
const text = await res.text();
|
|
try {
|
|
json = text ? JSON.parse(text) : null;
|
|
} catch {
|
|
json = null;
|
|
}
|
|
if (json && typeof json === "object" && "server_time" in json) {
|
|
const t = Date.parse(String((json as { server_time: string }).server_time));
|
|
if (!Number.isNaN(t)) events.onServerTime?.(t - Date.now());
|
|
}
|
|
if (!envelope(json)) {
|
|
if (res.status === 401) {
|
|
events.onSignedOut?.();
|
|
throw new SignedOut("signed out");
|
|
}
|
|
if (res.status >= 502 && res.status <= 504) {
|
|
if (!opts.quiet) events.onContact?.(false);
|
|
throw new LostContact(`proxy answered ${res.status}`);
|
|
}
|
|
events.onContact?.(true);
|
|
return { status: res.status, data: json as T, etag: res.headers.get("ETag") };
|
|
}
|
|
events.onContact?.(true);
|
|
const env = json;
|
|
if (env.error.code === "request.in_progress") {
|
|
await sleep(1000);
|
|
continue;
|
|
}
|
|
if (env.error.code === "rate.limited" && !rateRetried) {
|
|
rateRetried = true;
|
|
await sleep(Math.min(60, env.error.retry_after_s ?? 1) * 1000);
|
|
continue;
|
|
}
|
|
if (res.status === 401 && env.error.code.startsWith("token.")) {
|
|
// The UI holds no token: a token refusal means the sign-in did not reach control.
|
|
events.onSignedOut?.();
|
|
throw new SignedOut(env.error.message);
|
|
}
|
|
throw new ApiError(res.status, env.error, env.errors ?? [], env.request_id ?? "");
|
|
}
|
|
throw new ApiError(
|
|
409,
|
|
{
|
|
code: "request.in_progress",
|
|
message: "The first request with this Idempotency-Key is still being handled. Try again in a moment.",
|
|
field: null,
|
|
params: {},
|
|
retry_after_s: 1,
|
|
detail: null,
|
|
},
|
|
[],
|
|
"",
|
|
);
|
|
}
|
|
|
|
export const get = <T>(path: string, opts?: CallOptions) => call<T>("GET", path, undefined, opts).then((a) => a.data as T);
|
|
export const post = <T>(path: string, body: unknown = {}, opts?: CallOptions) =>
|
|
call<T>("POST", path, body, { idem: newKey(), ...opts }).then((a) => a.data as T);
|
|
export const put = <T>(path: string, body: unknown, opts?: CallOptions) =>
|
|
call<T>("PUT", path, body, { idem: newKey(), ...opts }).then((a) => a.data as T);
|
|
export const patch = <T>(path: string, body: unknown, opts?: CallOptions) =>
|
|
call<T>("PATCH", path, body, { idem: newKey(), ...opts }).then((a) => a.data as T);
|
|
export const del = (path: string, opts?: CallOptions) => call<unknown>("DELETE", path, undefined, opts).then(() => undefined);
|
|
|
|
/** A UI sentence for request.* codes (handoff §12.4): bugs or a stale page, not user mistakes. */
|
|
export function sentence(e: unknown): string {
|
|
if (e instanceof ApiError) {
|
|
if (e.code.startsWith("request.") && e.code !== "request.in_progress") {
|
|
return "Ianitor refused this request from the page. Reload the page and try again.";
|
|
}
|
|
return e.body.message;
|
|
}
|
|
if (e instanceof LostContact) return "Ianitor's control service is not answering. Traffic keeps flowing; changes wait until it is back.";
|
|
if (e instanceof SignedOut) return "Your sign-in has ended. Sign in again; this page keeps what you typed.";
|
|
return "Something went wrong.";
|
|
}
|