// The whole server contract, in one file. // // Types are hand-written to mirror the `Serialize` structs in // `crates/otserver/src/api.rs`. A Rust test (`api::tests::the_json_shape_is_the // _one_the_web_ui_expects`) asserts the exact JSON key set of every response // type, so a renamed field fails `cargo test` instead of failing in a browser. export interface Me { id: number; username: string; display_name: string; is_admin: boolean; server_time: number; } export interface Position { ts: number; /** Degrees x 1e7. Integers end to end, so no float-formatting drift. */ lat_e7: number; lon_e7: number; acc_dm: number | null; alt_m: number | null; spd_cms: number | null; brg_cdeg: number | null; bat_pct: number | null; flags: number; recv_at: number; } export interface PersonState { user_id: number; display_name: string; is_self: boolean; position?: Position; } export interface StateResponse { server_time: number; people: PersonState[]; } export interface TokenInfo { /** A decimal string: a u64 does not fit exactly in a JS number. */ token_id: string; name: string; platform: string; app_version: number | null; os_api_level: number | null; last_seen_at: number | null; last_src_ip: string | null; last_transport: string | null; created_at: number; } export interface TrackResponse { user_id: number; from: number; to: number; polyline: string; point_count: number; } export interface ShareInfo { id: number; viewer_user_id: number; viewer_username: string; viewer_display_name: string; trail_visible: boolean; precision_m: number; expires_at: number | null; created_at: number; } export interface CreateShare { username: string; trail_visible: boolean; precision_m: number; /** Seconds from now. `null` means the share does not expire. */ expires_in_s: number | null; } /** Point flag bits, matching `otproto::Point`. */ export const FLAG_CHARGING = 1; export const FLAG_NETWORK_FIX = 2; export const FLAG_LOW_ACCURACY = 4; export const FLAG_MOCK = 8; export class ApiError extends Error { constructor( readonly status: number, message: string, ) { super(message); } } /** Thrown-away sentinel: the caller shows the login screen on a 401. */ export const UNAUTHORIZED = 401; async function request(method: string, path: string, body?: unknown, etag?: string): Promise<{ data: T | null; etag: string | null }> { const headers: Record = {}; // A custom header a cross-origin page cannot set without a CORS preflight we // never grant. Combined with SameSite=Lax on the session cookie that is the // whole CSRF defence; there is no token to store or rotate. if (method !== "GET") headers["X-OT-CSRF"] = "1"; if (body !== undefined) headers["Content-Type"] = "application/json"; if (etag) headers["If-None-Match"] = etag; const res = await fetch(path, { method, headers, credentials: "same-origin", body: body === undefined ? undefined : JSON.stringify(body), }); if (res.status === 304) return { data: null, etag: etag ?? null }; if (!res.ok) { const message = await res .json() .then((b) => (b as { error?: string }).error ?? res.statusText) .catch(() => res.statusText); throw new ApiError(res.status, message); } const responseEtag = res.headers.get("ETag"); if (res.status === 204) return { data: null, etag: responseEtag }; return { data: (await res.json()) as T, etag: responseEtag }; } async function json(method: string, path: string, body?: unknown): Promise { const { data } = await request(method, path, body); return data as T; } export const api = { login: (username: string, password: string) => json<{ user: Me }>("POST", "/api/login", { username, password }), logout: () => json("POST", "/api/logout"), me: () => json("GET", "/api/me"), /** Returns null when the ETag matched, meaning nothing changed. */ state: (etag?: string) => request("GET", "/api/state", undefined, etag), tokens: () => json("GET", "/api/tokens"), revokeToken: (id: string) => json("DELETE", `/api/tokens/${id}`), revokeOthers: () => json<{ revoked: number }>("POST", "/api/tokens/revoke-others"), /** Outgoing, still-live shares only, newest first. */ shares: () => json("GET", "/api/shares"), createShare: (body: CreateShare) => json("POST", "/api/shares", body), revokeShare: (id: number) => json("DELETE", `/api/shares/${id}`), track: (userId: number, from: number, to: number, max = 2000) => json("GET", `/api/users/${userId}/track?from=${from}&to=${to}&max=${max}`), changePassword: (current_password: string, new_password: string) => json("POST", "/api/me/password", { current_password, new_password }), }; /** * Google encoded polyline at 1e5, the format `/track` returns. * * The server encodes; nothing here re-encodes, so this is the only half that * has to exist. */ export function decodePolyline(encoded: string): [number, number][] { const out: [number, number][] = []; let index = 0; let lat = 0; let lon = 0; while (index < encoded.length) { for (let i = 0; i < 2; i++) { let result = 0; let shift = 0; let byte: number; do { byte = encoded.charCodeAt(index++) - 63; result |= (byte & 0x1f) << shift; shift += 5; } while (byte >= 0x20); const delta = result & 1 ? ~(result >> 1) : result >> 1; if (i === 0) lat += delta; else lon += delta; } out.push([lat / 1e5, lon / 1e5]); } return out; }