HTTP requests identify Faceclaw in their user-agent string

This commit is contained in:
James Babcock committed 2026-08-20 11:32:50 -07:00
1 parent c27dcacfee
commit 8cdee2a701
14 files changed
+115 -9

No files matched your search

@@ -0,0 +1,42 @@
package com.faceclaw.app;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
/**
* Shared HTTP identity for the Java networking helpers. The version lives in
* app/version.ts, so the TypeScript side pushes the real string in at startup
* (see installNativeUserAgent in app/util/http.ts); the default below is only
* a fallback for requests that somehow beat that call.
*/
public final class FaceclawHttp {
private static volatile String userAgent = "Faceclaw";
private FaceclawHttp() {}
public static void setUserAgent(String value) {
if (value != null && !value.trim().isEmpty()) {
userAgent = value.trim();
}
}
public static String getUserAgent() {
return userAgent;
}
/** Stamps our User-Agent on any request that doesn't already carry one. */
public static Interceptor userAgentInterceptor() {
return new Interceptor() {
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (request.header("User-Agent") != null) {
return chain.proceed(request);
}
return chain.proceed(request.newBuilder().header("User-Agent", userAgent).build());
}
};
}
}
@@ -63,6 +63,7 @@ public class FaceclawModelDownloader {
sharedClient = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.addInterceptor(FaceclawHttp.userAgentInterceptor())
.build();
}
}
@@ -134,6 +134,7 @@ public class FaceclawSseRequest {
sharedClient = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.readTimeout(180, TimeUnit.SECONDS)
.addInterceptor(FaceclawHttp.userAgentInterceptor())
.build();
}
client = sharedClient;
@@ -112,6 +112,7 @@ public class FaceclawWebSocket {
if (sharedClient == null) {
sharedClient = new OkHttpClient.Builder()
.pingInterval(20, TimeUnit.SECONDS)
.addInterceptor(FaceclawHttp.userAgentInterceptor())
.build();
}
client = sharedClient;
+2
View File
@@ -6,7 +6,9 @@ purpose of the file is to pass control to the app’s first module.
import { Application } from '@nativescript/core'
import { registerShareIntentHandler } from './native/share-intents'
import { installNativeUserAgent } from './util/http'
installNativeUserAgent()
registerShareIntentHandler()
Application.run({ moduleName: 'app-root' })
+2 -1
View File
@@ -7,6 +7,7 @@
*/
import { Application } from "@nativescript/core";
import { evenHubEmailSetting, evenHubPasswordSetting, hasEvenHubCredentials } from "./credentials";
import { fetchWithUserAgent } from "../../util/http";
declare const android: any;
@@ -325,7 +326,7 @@ async function fetchWithTimeout(url: string, init: RequestInit, timeoutMs = REQU
timeoutHandle = setTimeout(() => reject(new Error("EvenHub request timed out.")), timeoutMs);
});
try {
return await Promise.race([fetch(url, init), timeout]);
return await Promise.race([fetchWithUserAgent(url, init), timeout]);
} finally {
if (timeoutHandle) clearTimeout(timeoutHandle);
}
+2 -1
View File
@@ -1,4 +1,5 @@
import { Application } from "@nativescript/core";
import { fetchWithUserAgent } from "../../util/http";
declare const android: any;
declare const androidx: any;
@@ -74,7 +75,7 @@ async function downloadAndOpenPdf(url: string, appName: string, activity: any):
});
let response: Response;
try {
response = await Promise.race([fetch(url), timeout]);
response = await Promise.race([fetchWithUserAgent(url), timeout]);
} finally {
if (timeoutHandle) clearTimeout(timeoutHandle);
}
+2 -1
View File
@@ -6,6 +6,7 @@
* worker via fetch.
*/
import { roamApiTokenSetting, roamGraphNameSetting } from "../../ui/dashboard-settings";
import { fetchWithUserAgent } from "../../util/http";
const API_BASE = "https://api.roamresearch.com";
const FETCH_TIMEOUT_MS = 12_000;
@@ -145,7 +146,7 @@ async function roamPost(endpoint: "q" | "pull" | "write", body: object): Promise
async function fetchWithTimeout(url: string, payload: string, token: string): Promise<Response> {
let timeoutHandle: ReturnType<typeof setTimeout> | null = null;
const request = fetch(url, {
const request = fetchWithUserAgent(url, {
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8",
+2 -1
View File
@@ -18,6 +18,7 @@ import {
extractEvenHubFontAsset,
isEvenHubFontAsset,
} from "./firmware-fonts";
import { fetchWithUserAgent } from "../util/http";
declare const com: any;
@@ -157,7 +158,7 @@ async function downloadAndVerifyBase(report: (progress: FirmwareProgress) => voi
async function downloadFirmware(): Promise<ArrayBuffer> {
let response: Response;
try {
response = await fetch(FIRMWARE_URL);
response = await fetchWithUserAgent(FIRMWARE_URL);
} catch (error) {
throw new FirmwareBuildError(`Could not reach Even's firmware CDN: ${(error as Error)?.message ?? error}`);
}
+2 -1
View File
@@ -7,6 +7,7 @@
import { GrayImage } from "../graphics/image";
import { getStringSetting } from "./settings-store";
import { grayImageFromPacket } from "./image-files";
import { fetchWithUserAgent } from "../util/http";
declare const com: any;
declare const global: any;
@@ -268,7 +269,7 @@ async function fetchJson(url: string, label: string): Promise<any> {
}
async function fetchWithTimeout(url: string, label: string): Promise<Response> {
const request = fetch(url);
const request = fetchWithUserAgent(url);
let timeoutHandle: ReturnType<typeof setTimeout> | null = null;
const timeout = new Promise<never>((_resolve, reject) => {
timeoutHandle = setTimeout(() => reject(new Error(`${label} timed out.`)), FETCH_TIMEOUT_MS);
+2 -1
View File
@@ -1,4 +1,5 @@
import { loadNightscoutSettings, nightscoutApiTokenSetting, nightscoutSiteUrlSetting } from "../ui/dashboard-settings";
import { fetchWithUserAgent } from "../util/http";
export type NightscoutPoint = {
timestampMs: number;
@@ -292,7 +293,7 @@ export class NightscoutBridge {
}
async function fetchJson<T>(url: string): Promise<T> {
const response = await fetch(url);
const response = await fetchWithUserAgent(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
+5 -2
View File
@@ -1,5 +1,7 @@
import { hasLocationPermission } from "../g2/android-permissions";
import { getCurrentLocation, type CurrentLocation } from "./location";
import { fetchWithUserAgent } from "../util/http";
import { USER_AGENT } from "../version";
export type WeatherPhase = "permission-required" | "locating" | "loading" | "ready" | "error";
@@ -87,7 +89,8 @@ type NwsMeasure = {
const NWS_API_ROOT = "https://api.weather.gov";
const NWS_HEADERS = {
Accept: "application/geo+json",
"User-Agent": "Faceclaw/1.0 (https://github.com/jimrandomh/faceclaw)",
// NWS asks callers to identify themselves with a contact address.
"User-Agent": `${USER_AGENT} (https://github.com/jimrandomh/faceclaw)`,
};
const WEATHER_REFRESH_MS = 30 * 60 * 1000;
const FETCH_TIMEOUT_MS = 20_000;
@@ -230,7 +233,7 @@ async function loadLatestObservation(stationsUrl: string): Promise<NwsObservatio
}
async function fetchNwsJson<T>(url: string): Promise<T> {
const request = fetch(url, { headers: NWS_HEADERS });
const request = fetchWithUserAgent(url, { headers: NWS_HEADERS });
let timeoutHandle: ReturnType<typeof setTimeout> | null = null;
const timeout = new Promise<never>((_resolve, reject) => {
timeoutHandle = setTimeout(() => reject(new Error("Weather request timed out.")), FETCH_TIMEOUT_MS);
+49
View File
@@ -0,0 +1,49 @@
import { USER_AGENT } from "../version";
declare const com: any;
/**
* fetch() with our User-Agent attached. Every outbound HTTP request in the app
* should go through this instead of calling fetch() directly, so servers see a
* consistent, identifiable client string. A User-Agent the caller supplies
* explicitly wins (e.g. an API that wants contact details appended).
*
* Requests made from the Java side (FaceclawSseRequest, FaceclawWebSocket,
* FaceclawModelDownloader) get the same header from FaceclawHttp's okhttp
* interceptor.
*/
export function fetchWithUserAgent(url: string, init?: RequestInit): Promise<Response> {
return fetch(url, { ...init, headers: withUserAgent(init?.headers) });
}
/** Copies headers into a plain record, adding our User-Agent if absent. */
export function withUserAgent(headers?: HeadersInit): Record<string, string> {
const merged: Record<string, string> = {};
if (headers) {
if (Array.isArray(headers)) {
for (const [name, value] of headers) merged[name!] = value!;
} else if (typeof (headers as Headers).forEach === "function") {
(headers as Headers).forEach((value, name) => {
merged[name] = value;
});
} else {
Object.assign(merged, headers as Record<string, string>);
}
}
const hasUserAgent = Object.keys(merged).some((name) => name.toLowerCase() === "user-agent");
if (!hasUserAgent) merged["User-Agent"] = USER_AGENT;
return merged;
}
/**
* Hands our User-Agent to the Java networking helpers. Called once during app
* startup; the value is a process-wide static, so workers pick it up too.
*/
export function installNativeUserAgent(): void {
if (!global.isAndroid) return;
try {
com.faceclaw.app.FaceclawHttp.setUserAgent(USER_AGENT);
} catch {
// Non-fatal: okhttp falls back to FaceclawHttp's built-in default.
}
}
+2 -1
View File
@@ -1 +1,2 @@
export const FACECLAW_VERSION = "0.4.0";
export const FACECLAW_VERSION = "0.4.1";
export const USER_AGENT = "Faceclaw/"+FACECLAW_VERSION;