Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/plugin-runtime/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"domhandler": "^6.0.1",
"env-paths": "^4.0.0",
"htmlparser2": "^9.1.0",
"impit": "^0.14.9",
"jszip": "^3.10.2",
"protobufjs": "^7.6.6",
"sanitize-html": "^2.17.7",
Expand Down
22 changes: 21 additions & 1 deletion packages/plugin-runtime/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,26 @@ function* chain(err: unknown): Generator<unknown> {
}
}

/**
* Detect impit's `TransportError` hierarchy without importing `impit` at module
* load time (which fails on platforms without a prebuilt native binary).
*/
function isImpitTransportError(err: unknown): boolean {
if (!(err instanceof Error)) return false;
let seenTransport = false;
for (
let proto = Object.getPrototypeOf(err);
proto && proto !== Error.prototype;
proto = Object.getPrototypeOf(proto)
) {
const name = (proto as { constructor?: { name?: string } }).constructor
?.name;
if (name === 'TransportError') seenTransport = true;
if (seenTransport && name === 'ImpitError') return true;
}
return false;
}

/**
* Map any thrown value to `{ code, message, hint }`. The first
* `LnreaderError` in the cause chain wins, so a bot check inside a plugin
Expand All @@ -121,7 +141,7 @@ export function errorInfo(err: unknown): ErrorInfo {
}
}
for (const e of chain(err)) {
if (e instanceof HttpError)
if (e instanceof HttpError || isImpitTransportError(e))
return {
code: 'NETWORK',
message,
Expand Down
25 changes: 2 additions & 23 deletions packages/plugin-runtime/src/net/client.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { CookieJar } from 'tough-cookie';
import { ChallengeError, HttpError } from '../errors.js';
import { createImpitFetch, toHeaders } from './impit.js';
import { HostLimiter, type LimiterOptions } from './limiter.js';

export type FetchLike = (
Expand All @@ -26,12 +27,6 @@ export type HttpClientOptions = LimiterOptions & {
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
};

const DEFAULT_HEADERS: Record<string, string> = {
Accept: '*/*',
'Accept-Language': 'en-US,en;q=0.9',
'Sec-Fetch-Mode': 'cors',
};

const REDIRECTS = new Set([301, 302, 303, 307, 308]);

export { HttpError };
Expand Down Expand Up @@ -83,18 +78,6 @@ export async function isChallenge(res: Response): Promise<boolean> {
}
}

type HeadersInit = ConstructorParameters<typeof Headers>[0];

function toHeaders(init: HeadersInit | undefined): Headers {
const headers = new Headers();
if (init) {
const source =
init instanceof Headers ? init : new Headers(init as HeadersInit);
source.forEach((v, k) => headers.set(k, v));
}
return headers;
}

/**
* Polite HTTP client: per-host rate limiting, cookie jars that also see
* redirect hops, and retries with exponential backoff honoring `Retry-After`.
Expand All @@ -106,8 +89,7 @@ export class HttpClient {

constructor(private readonly options: HttpClientOptions) {
this.limiter = new HostLimiter(options);
this.fetchImpl =
options.fetch ?? ((input, init) => globalThis.fetch(input, init));
this.fetchImpl = options.fetch ?? createImpitFetch();
this.sleep = options.sleep ?? sleep;
}

Expand Down Expand Up @@ -164,9 +146,6 @@ export class HttpClient {
let method = (init.method ?? 'GET').toUpperCase();
let body = init.body;
const baseHeaders = toHeaders(init.headers);
for (const [k, v] of Object.entries(DEFAULT_HEADERS)) {
if (!baseHeaders.has(k)) baseHeaders.set(k, v);
}
if (!baseHeaders.has('user-agent'))
baseHeaders.set('user-agent', opts.userAgent ?? this.options.userAgent);

Expand Down
117 changes: 117 additions & 0 deletions packages/plugin-runtime/src/net/impit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import type { RequestInit as ImpitRequestInit } from 'impit';
import { DEFAULT_USER_AGENT } from '../store/config.js';
import type { FetchLike } from './client.js';

type HeadersInit = ConstructorParameters<typeof Headers>[0];

export function toHeaders(init: HeadersInit | undefined): Headers {
const headers = new Headers();
if (init) {
const source =
init instanceof Headers ? init : new Headers(init as HeadersInit);
source.forEach((v, k) => headers.set(k, v));
}
return headers;
}

function secFetchSite(url: string, headers: Headers): string {
const source = headers.get('origin') ?? headers.get('referer');
if (!source) return 'none';
try {
return new URL(source).origin === new URL(url).origin
? 'same-origin'
: 'cross-site';
} catch {
return 'same-origin';
}
}

/**
* Adjusts only context-dependent headers (`Sec-Fetch-*` and custom
* `User-Agent` overrides) while leaving static browser headers (`Accept`,
* `Accept-Encoding`, `Accept-Language`, `Priority`, `Sec-CH-UA*`, `User-Agent`)
* to impit's browser profile.
*/
function adaptHeaders(
url: string,
method: string,
init: HeadersInit | undefined,
): Headers {
const headers = toHeaders(init);
const ua = headers.get('user-agent');
if (ua === DEFAULT_USER_AGENT) {
headers.delete('user-agent');
} else if (ua) {
for (const h of ['sec-ch-ua', 'sec-ch-ua-mobile', 'sec-ch-ua-platform']) {
if (!headers.has(h)) headers.set(h, '');
}
}

if (!headers.has('sec-fetch-site')) {
headers.set('sec-fetch-site', secFetchSite(url, headers));
}

const accept = headers.get('accept');
const isImage = method === 'GET' && !!accept?.startsWith('image/');
const isXhr =
!isImage &&
(method !== 'GET' ||
headers.has('x-requested-with') ||
headers.has('origin') ||
headers.has('content-type') ||
headers.has('authorization') ||
(accept !== null && !accept.includes('text/html')));
Comment thread
trietng marked this conversation as resolved.
Resolved

if (isImage) {
if (!headers.has('sec-fetch-mode'))
headers.set('sec-fetch-mode', 'no-cors');
if (!headers.has('sec-fetch-dest')) headers.set('sec-fetch-dest', 'image');
if (!headers.has('sec-fetch-user')) headers.set('sec-fetch-user', '');
if (!headers.has('upgrade-insecure-requests'))
headers.set('upgrade-insecure-requests', '');
} else if (isXhr) {
if (!headers.has('accept')) headers.set('accept', '*/*');
if (!headers.has('sec-fetch-mode')) headers.set('sec-fetch-mode', 'cors');
if (!headers.has('sec-fetch-dest')) headers.set('sec-fetch-dest', 'empty');
if (!headers.has('sec-fetch-user')) headers.set('sec-fetch-user', '');
if (!headers.has('upgrade-insecure-requests'))
headers.set('upgrade-insecure-requests', '');
}
return headers;
}

const FALLBACK_HEADERS: Record<string, string> = {
Accept: '*/*',
'Accept-Language': 'en-US,en;q=0.9',
'Sec-Fetch-Mode': 'cors',
};

export function createImpitFetch(
load: () => Promise<typeof import('impit')> = () => import('impit'),
): FetchLike {
let implPromise: Promise<FetchLike> | undefined;
const resolveImpl = (): Promise<FetchLike> =>
(implPromise ??= (async (): Promise<FetchLike> => {
try {
const { Impit } = await load();
const impit = new Impit({ browser: 'chrome151', timeout: null });
return (input, init = {}) => {
const method = (init.method ?? 'GET').toUpperCase();
return impit.fetch(input, {
...(init as ImpitRequestInit),
headers: adaptHeaders(input, method, init.headers),
}) as unknown as Promise<Response>;
};
} catch {
return (input, init = {}) => {
const headers = toHeaders(init.headers);
for (const [k, v] of Object.entries(FALLBACK_HEADERS)) {
if (!headers.has(k)) headers.set(k, v);
}
return globalThis.fetch(input, { ...init, headers });
};
}
})());

return async (input, init) => (await resolveImpl())(input, init);
}
9 changes: 7 additions & 2 deletions packages/plugin-runtime/src/plugins/sandbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,11 @@ export function loadPlugin(
id: string,
options: SandboxOptions,
): Plugin.PluginBase {
const { modules, fetch } = createShims(options);
const pluginRef: { current?: Plugin.PluginBase } = {};
const { modules, fetch } = createShims({
...options,
defaultReferer: options.defaultReferer ?? (() => pluginRef.current?.site),
});
const module = { exports: {} as Record<string, unknown> };
const context = vm.createContext({
module,
Expand Down Expand Up @@ -109,7 +113,8 @@ export function loadPlugin(
timeout: options.loadTimeoutMs ?? 5_000,
});
const exported = module.exports.default ?? module.exports;
return assertPluginShape(exported, id);
pluginRef.current = assertPluginShape(exported, id);
return pluginRef.current;
}

/**
Expand Down
28 changes: 25 additions & 3 deletions packages/plugin-runtime/src/plugins/shims/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import protobuf from 'protobufjs';
import type { CookieJar } from 'tough-cookie';
import { ChallengeError } from '../../errors.js';
import type { HttpClient } from '../../net/client.js';
import { toHeaders } from '../../net/impit.js';
import { currentSignal } from '../context.js';

export type FetchInit = {
Expand All @@ -23,6 +24,8 @@ export type FetchShimDeps = {
jar: CookieJar;
/** User-Agent for this plugin's requests (see `lnreader auth`). */
userAgent?: string;
/** Plugin site URL used as the default `Referer` when a request omits one. */
defaultReferer?: () => string | undefined;
};

type HeadersInit = ConstructorParameters<typeof Headers>[0];
Expand All @@ -45,13 +48,32 @@ function toRequestInit(init?: FetchInit): RequestInit {
}

/** `@libs/fetch`, routed through the rate-limited client and the plugin's cookie jar. */
export function createFetchShim({ http, jar, userAgent }: FetchShimDeps) {
const fetchApi = (url: string, init?: FetchInit): Promise<Response> =>
http.request(String(url), toRequestInit(init), {
export function createFetchShim({
http,
jar,
userAgent,
defaultReferer,
}: FetchShimDeps) {
const fetchApi = (url: string, init?: FetchInit): Promise<Response> => {
const reqInit = toRequestInit(init);
const site = defaultReferer?.();
if (site) {
const headers = toHeaders(reqInit.headers);
if (!headers.has('referer')) {
try {
headers.set('referer', `${new URL(site).origin}/`);
} catch {
// Leave unset if site is not a valid URL.
}
}
reqInit.headers = headers;
}
return http.request(String(url), reqInit, {
jar,
userAgent,
signal: currentSignal(),
});
};

const fetchText = async (
url: string,
Expand Down
2 changes: 1 addition & 1 deletion packages/plugin-runtime/src/store/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export const DEFAULT_REPO =
'https://raw.githubusercontent.com/LNReader/lnreader-plugins/plugins/v3.0.0/.dist/plugins.min.json';

export const DEFAULT_USER_AGENT =
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36';
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/151.0.0.0 Safari/537.36';

export const ConfigSchema = z.object({
repos: z.array(z.url()).default([DEFAULT_REPO]),
Expand Down
Loading
Loading