Site-agnostic parts of the X app, behind a small site adapter: - crates/waybetter-host: webview-label security policy and tab rect clamp, account profiles with native-owned accounts (AccountRules), plugin store with bundled-plugin upgrades (PluginHost), signed data-only hotfix channel, update scheduling and crash handshake, tab payloads/link routing/tab-chrome validation, and (feature "tauri") webview helpers and the Windows system menu. - packages/runtime: DOM hub, request hub, plugin API core, OKLab theme color model, split-view rail hiding, link routing and account reporting, each configured by a SiteAdapter. - packages/shell: address bar, pane, link-drop, profile, palette and update-chip models, and window controls with the Tauri API injected. Tests moved/adapted from the app: 45 Rust (headless), 40 TypeScript.
252 lines
11 KiB
TypeScript
252 lines
11 KiB
TypeScript
// One shared fetch/XHR hook per window for everything a site runtime does with the site's own
|
|
// requests: URL rewrites, gates (e.g. serializing racing mutations) and passive JSON taps. Each
|
|
// feature registers a stage instead of stacking its own wrapper. A request whose URL contains none
|
|
// of the site's API marks (images, video, WASM, scripts, telemetry) takes one substring check and
|
|
// goes straight to the wrapped fetch, and a tapped response is cloned, read and JSON-parsed once for
|
|
// all taps. Semantics are unchanged: the page gets the very promise (and Response) the inner fetch
|
|
// returned unless a gate answers a request itself, rejections and aborts pass through, and nothing
|
|
// here ever issues a request of its own.
|
|
|
|
/** `input`/`init` are fetch's arguments; returns the rewritten URL, or null to leave the request alone. */
|
|
export type Rewrite = (input: unknown, init: RequestInit | undefined) => string | null;
|
|
/** Returns null when the request is not the gate's; otherwise the promise the page gets instead of `send()`. */
|
|
export type Gate = (input: unknown, init: RequestInit | undefined, send: () => Promise<Response>) => Promise<Response> | null;
|
|
export type Tap = { match(url: string): boolean; maxBytes: number; onJson(body: unknown): void };
|
|
/** XHR counterpart of `Gate` (many web clients still send their API calls with XMLHttpRequest). */
|
|
export type XhrGate = {
|
|
/**
|
|
* The page (re)opens this XHR object; called before the native `open`. Returning a string opens
|
|
* that URL instead (a request rewrite, like `Rewrite` for fetch).
|
|
*/
|
|
open?(xhr: XMLHttpRequest, request: { method: string; url: string }): string | void;
|
|
/**
|
|
* The page calls `send(body)` on an API (or XHR-mark) request. Returns true when the gate took it
|
|
* over: it then calls `sendNative()` itself (now or later; `sendNative(body)` sends that body
|
|
* instead of the page's) or completes the XHR on its own.
|
|
*/
|
|
send(xhr: XMLHttpRequest, request: { method: string; url: string }, body: unknown, sendNative: (...body: [] | [unknown]) => void): boolean;
|
|
};
|
|
|
|
export type NetHubConfig = {
|
|
/** URL substrings of the site's API calls; only these reach rewrites, gates and taps. */
|
|
apiMarks: string[];
|
|
/** Extra URL substrings that reach XHR gates only (e.g. a chunked media upload endpoint). */
|
|
xhrMarks: string[];
|
|
};
|
|
|
|
type HubWindow = {
|
|
fetch: typeof fetch;
|
|
XMLHttpRequest?: typeof XMLHttpRequest;
|
|
requestIdleCallback?: (callback: () => void, options?: { timeout: number }) => number;
|
|
};
|
|
|
|
type Hub = {
|
|
rewrites: Rewrite[];
|
|
gates: Gate[];
|
|
taps: Tap[];
|
|
xhrGates: XhrGate[];
|
|
hooked(): boolean;
|
|
add<T>(list: T[], item: T): () => void;
|
|
};
|
|
|
|
const config: NetHubConfig = { apiMarks: [], xhrMarks: [] };
|
|
const hubs = new WeakMap<object, Hub>();
|
|
|
|
/** Set once by the site adapter, before stages register. */
|
|
export function configureNetHub(next: Partial<NetHubConfig>): void {
|
|
if (next.apiMarks) config.apiMarks = [...next.apiMarks];
|
|
if (next.xhrMarks) config.xhrMarks = [...next.xhrMarks];
|
|
}
|
|
|
|
const hasMark = (url: string, marks: string[]) => {
|
|
for (const mark of marks) if (url.includes(mark)) return true;
|
|
return false;
|
|
};
|
|
|
|
/** Whether `url` is one of the site's API calls (plain substring checks, no URL parsing). */
|
|
export function isApiUrl(url: string): boolean {
|
|
return hasMark(url, config.apiMarks);
|
|
}
|
|
|
|
/** The request URL as given (string, URL or Request), without parsing it. */
|
|
export function rawUrl(input: unknown): string {
|
|
try {
|
|
if (typeof input === 'string') return input;
|
|
if (input instanceof URL) return input.href;
|
|
if (input && typeof (input as Request).url === 'string') return (input as Request).url;
|
|
} catch { /* ignore */ }
|
|
return '';
|
|
}
|
|
|
|
function hubFor(target: HubWindow): Hub {
|
|
const existing = hubs.get(target);
|
|
if (existing) return existing;
|
|
|
|
let inner: typeof fetch | null = null;
|
|
let wrapper: typeof fetch | null = null;
|
|
const proto: XMLHttpRequest | undefined = target.XMLHttpRequest?.prototype;
|
|
let originalOpen: XMLHttpRequest['open'] | undefined;
|
|
let openWrapper: XMLHttpRequest['open'] | undefined;
|
|
let originalSend: XMLHttpRequest['send'] | undefined;
|
|
let sendWrapper: XMLHttpRequest['send'] | undefined;
|
|
const opened = new WeakMap<XMLHttpRequest, { method: string; url: string }>();
|
|
|
|
const later = (run: () => void) => {
|
|
// Parsing a large body is the expensive part; keep it out of the page's own response handling.
|
|
const idle = target.requestIdleCallback;
|
|
if (typeof idle === 'function') { try { idle.call(target, run, { timeout: 200 }); return; } catch { /* fall through */ } }
|
|
run();
|
|
};
|
|
const deliver = (taps: Tap[], text: string) => {
|
|
const live = taps.filter(tap => hub.taps.includes(tap) && text.length <= tap.maxBytes);
|
|
if (!live.length) return;
|
|
later(() => {
|
|
let body: unknown;
|
|
try { body = JSON.parse(text); } catch { return; }
|
|
for (const tap of live) {
|
|
if (!hub.taps.includes(tap)) continue;
|
|
try { tap.onJson(body); } catch { /* A consumer failure never reaches the page. */ }
|
|
}
|
|
});
|
|
};
|
|
const matchingTaps = (url: string) => hub.taps.length ? hub.taps.filter(tap => { try { return tap.match(url); } catch { return false; } }) : [];
|
|
|
|
const fetchWrapper = function (this: unknown, ...args: Parameters<typeof fetch>): Promise<Response> {
|
|
const url = rawUrl(args[0]);
|
|
if (!hasMark(url, config.apiMarks)) return Reflect.apply(inner!, this, args) as Promise<Response>;
|
|
let [input, init] = args;
|
|
for (const rewrite of hub.rewrites) {
|
|
const next = rewrite(input, init);
|
|
if (next != null) input = next;
|
|
}
|
|
const call = input === args[0] ? args : [input, init] as Parameters<typeof fetch>;
|
|
const send = () => Reflect.apply(inner!, this, call) as Promise<Response>;
|
|
let result: Promise<Response> | null = null;
|
|
for (const gate of hub.gates) {
|
|
result = gate(input, init, send);
|
|
if (result) break;
|
|
}
|
|
result ??= send();
|
|
const taps = matchingTaps(rawUrl(input));
|
|
if (taps.length) {
|
|
result.then(response => {
|
|
if (!response.ok) return;
|
|
const length = Number(response.headers.get('content-length') ?? 0);
|
|
if (!taps.some(tap => hub.taps.includes(tap) && length <= tap.maxBytes)) return;
|
|
return response.clone().text().then(text => deliver(taps, text));
|
|
}).catch(() => {});
|
|
}
|
|
return result;
|
|
};
|
|
|
|
const onLoad = function (this: XMLHttpRequest, taps: Tap[]) {
|
|
try {
|
|
if (this.status < 200 || this.status >= 300) return;
|
|
if (this.responseType === '' || this.responseType === 'text') deliver(taps, this.responseText);
|
|
else if (this.responseType === 'json' && this.response) {
|
|
const body = this.response;
|
|
for (const tap of taps) if (hub.taps.includes(tap)) { try { tap.onJson(body); } catch { /* ignore */ } }
|
|
}
|
|
} catch { /* ignore */ }
|
|
};
|
|
|
|
const install = () => {
|
|
if (!wrapper && (hub.rewrites.length || hub.gates.length || hub.taps.length)) {
|
|
inner = target.fetch;
|
|
try { target.fetch = fetchWrapper; wrapper = fetchWrapper; } catch { /* Readonly runtime. */ }
|
|
}
|
|
if (!proto) return;
|
|
if (!openWrapper && (hub.taps.length || hub.xhrGates.length)) {
|
|
const open = originalOpen = proto.open;
|
|
const candidate = function (this: XMLHttpRequest, ...args: unknown[]) {
|
|
try {
|
|
let url = String(args[1]);
|
|
if (hub.xhrGates.length) {
|
|
const method = String(args[0]).toUpperCase();
|
|
for (const gate of hub.xhrGates) {
|
|
const next = gate.open?.(this, { method, url });
|
|
if (typeof next === 'string') { url = next; args = [args[0], next, ...args.slice(2)]; }
|
|
}
|
|
opened.set(this, { method, url });
|
|
} else opened.delete(this);
|
|
if (hasMark(url, config.apiMarks)) {
|
|
const taps = matchingTaps(url);
|
|
if (taps.length) this.addEventListener('load', function (this: XMLHttpRequest) { onLoad.call(this, taps); }, { once: true });
|
|
}
|
|
} catch { /* ignore */ }
|
|
return Reflect.apply(open, this, args);
|
|
} as XMLHttpRequest['open'];
|
|
try { proto.open = candidate; openWrapper = candidate; } catch { /* ignore */ }
|
|
}
|
|
if (!sendWrapper && hub.xhrGates.length) {
|
|
const send = originalSend = proto.send;
|
|
const candidate: XMLHttpRequest['send'] = function (this: XMLHttpRequest, ...args) {
|
|
const request = opened.get(this);
|
|
if (request && (hasMark(request.url, config.apiMarks) || hasMark(request.url, config.xhrMarks))) {
|
|
const sendNative = (...body: [] | [unknown]) => { Reflect.apply(send, this, body.length ? body : args); };
|
|
for (const gate of hub.xhrGates) if (gate.send(this, request, args[0], sendNative)) return;
|
|
}
|
|
return Reflect.apply(send, this, args);
|
|
};
|
|
try { proto.send = candidate; sendWrapper = candidate; } catch { /* ignore */ }
|
|
}
|
|
};
|
|
const uninstall = () => {
|
|
// Anyone still holding a wrapper (another script wrapped on top) gets plain pass-through.
|
|
if (proto && openWrapper && !hub.taps.length && !hub.xhrGates.length && proto.open === openWrapper) {
|
|
proto.open = originalOpen!;
|
|
openWrapper = undefined;
|
|
}
|
|
if (proto && sendWrapper && !hub.xhrGates.length && proto.send === sendWrapper) {
|
|
proto.send = originalSend!;
|
|
sendWrapper = undefined;
|
|
}
|
|
if (!hub.rewrites.length && !hub.gates.length && !hub.taps.length && wrapper) {
|
|
if (target.fetch === wrapper) { target.fetch = inner!; wrapper = null; }
|
|
}
|
|
};
|
|
|
|
const hub: Hub = {
|
|
rewrites: [],
|
|
gates: [],
|
|
taps: [],
|
|
xhrGates: [],
|
|
hooked: () => wrapper !== null && target.fetch === wrapper,
|
|
add(list, item) {
|
|
list.push(item);
|
|
install();
|
|
let removed = false;
|
|
return () => {
|
|
if (removed) return;
|
|
removed = true;
|
|
const index = list.indexOf(item);
|
|
if (index >= 0) list.splice(index, 1);
|
|
uninstall();
|
|
};
|
|
},
|
|
};
|
|
hubs.set(target, hub);
|
|
return hub;
|
|
}
|
|
|
|
/** Whether the shared hook is installed as `target.fetch` (for callers that report `installed`). */
|
|
export function fetchHooked(target: HubWindow): boolean {
|
|
return hubs.get(target)?.hooked() ?? false;
|
|
}
|
|
|
|
export function addRewrite(target: HubWindow, rewrite: Rewrite): () => void {
|
|
const hub = hubFor(target);
|
|
return hub.add(hub.rewrites, rewrite);
|
|
}
|
|
export function addGate(target: HubWindow, gate: Gate): () => void {
|
|
const hub = hubFor(target);
|
|
return hub.add(hub.gates, gate);
|
|
}
|
|
export function addTap(target: HubWindow, tap: Tap): () => void {
|
|
const hub = hubFor(target);
|
|
return hub.add(hub.taps, tap);
|
|
}
|
|
export function addXhrGate(target: HubWindow, gate: XhrGate): () => void {
|
|
const hub = hubFor(target);
|
|
return hub.add(hub.xhrGates, gate);
|
|
}
|