clove/authServer
src/lib/http.ts
/* src/lib/http.ts
* Copyright (c) 2026 Clove Nytrix Doughmination Twilight
* Licensed under the DASL-1.2 Licence.
* See LICENCE.md in the project root for full licence information.
*/
import type { ContentfulStatusCode } from "hono/utils/http-status";
import type { AppContext } from "../env";
export function clientIp(c: AppContext): string {
return c.req.header("cf-connecting-ip") ?? "unknown";
}
export function userAgent(c: AppContext): string {
return (c.req.header("user-agent") ?? "").slice(0, 300);
}
/** Only same-site paths: "/x" yes, "//host", "/\host" and absolute URLs no. */
export function safeReturn(raw: unknown, fallback = "/apps"): string {
if (typeof raw !== "string" || !raw.startsWith("/")) return fallback;
if (raw.startsWith("//") || raw.startsWith("/\\")) return fallback;
if (/[\x00-\x1f\x7f]/.test(raw)) return fallback;
return raw.length > 4096 ? fallback : raw;
}
/** Parsed form body with every value coerced to a string (files dropped). For the OIDC endpoints. */
export async function form(c: AppContext): Promise<Record<string, string>> {
const body = await c.req.parseBody({ all: true });
const out: Record<string, string> = {};
for (const [key, value] of Object.entries(body)) {
const first = Array.isArray(value) ? value[0] : value;
if (typeof first === "string") out[key] = first;
}
return out;
}
export function lines(input: string | undefined): string[] {
return (input ?? "")
.split(/[\r\n]+/)
.map((l) => l.trim())
.filter(Boolean);
}
export async function readJson<T>(c: AppContext): Promise<T | null> {
try {
return (await c.req.json()) as T;
} catch {
return null;
}
}
/** An /api request body: always an object, whatever was (or wasn't) sent. */
export async function body(c: AppContext): Promise<Record<string, unknown>> {
const parsed = await readJson<unknown>(c);
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : {};
}
/** A body field as a string; anything else (missing, a number, an object) is "". */
export function str(value: unknown): string {
return typeof value === "string" ? value : "";
}
/** A body field as a list of strings (checkbox groups). */
export function strings(value: unknown): string[] {
return Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : [];
}
/** The /api error shape: `{ error }`, plus anything the page needs to react (e.g. `reauth`). */
export function fail(c: AppContext, error: string, status: ContentfulStatusCode = 400, extra: object = {}) {
return c.json({ error, ...extra }, status);
}