Legado Compatibility & Server Adapter Guide
Technical contract for Legado (Reading 3.0) rule and script compatibility in Origo X (semantics v26), including the QuickJS/JSC worker sandbox, built-in CryptoJS, session replay, SSRF guard, and orsp-converter.
In questa pagina
Origo X supports both modern open-protocol sources (ORSP 1.6) and locally imported Legado (Reading 3.0) rule-based sources. This reference documents the compatibility contract of Origo X's local SourceRuntime (SourceRuleEngine rule semantics v26) alongside the server-side orsp-converter bridge (orsp-legado-adapter).
Local Rule Engine Contract (Semantics v26)
Origo X implements a unified rule runtime aligned with Reading 3.0 semantics without introducing hardcoded domain, hostname, or source-name special cases into the core engine. Advancing rule semantics to v26 invalidates only derived parse caches on demand while preserving account sessions, source definitions, bookshelves, and reading progress.
1. Jsoup / CSS & Legacy Selectors
- Legacy Selector Alignment: Full support for
class.xxx,id.xxx,tag.xxx,text.xxx, and slice/index suffixes (class.0,.0,[0:5],[!0]).class.xxxmatches tokenized DOM class names directly—supporting colon-containing Tailwind classes (such asclass.hover:text-primary.0@text), escaped or digit-prefixed CSS classes, and disambiguating<title>/<data>tags from same-named attributes in list mode. - Modern CSS Pseudo-Classes: Supports
:nth-of-type(an+b),:nth-last-of-type(an+b),:first-of-type,:last-of-type,:only-of-type(indexed per same-tag siblings under each parent rather than filtered class matches, withodd,even, and signed formulas);:first-child,:last-child,:only-child,:nth-last-child(an+b),:empty,:root; multi-argument:not(a, b),:is(a, b),:where(a, b);:containsData,:containsWholeText,:containsWholeOwnText; relative:has(> / + / ~)combinators; and empty-value attribute selectors. - Multi-Paradigm Pipelines: Combines CSS/Jsoup, XPath, standard and recursive JSONPath,
##pattern##replacement/###regex transforms,@css/@json/@xpathprefixes, and sequential/fallback chains.
2. Balanced Parsing & Template Interpolation
@put:{...}and@get:{...}:@put:{...}uses balanced-brace scanning at any top-level position with support for multiple extraction blocks, preventing premature truncation on nested object literals or regex quantifiers.{{...}}Balanced Scanner: Lexes nested braces and string literals safely so embedded regex quantifiers (such as\d{2,4}) and JS object literals parse intact. Function calls and script expressions ({{GET('host')}},{{baseUrl.match(...)}}) are dispatched directly to the script context; explicit CSS/JSONPath/XPath rules keep their native evaluators; unprefixed keys continue resolving as JSON fields.
3. Watchdog-Protected Regex & Field Isolation
- Java Inline Flag Translation: Converts
(?i),(?s),(?m),(?-s),(?is-m), and scoped(?i:...)groups into DartRegExpflags while preserving syntax errors on malformed patterns. - 2-Second Isolate Watchdog: When an input string reaches
16,384characters or a pattern contains backtracking-prone constructs (quantified groups, backreferences\1, lookarounds(?=...), or chained greedy wildcards), evaluation runs inside a killable watchdog isolate with a strict 2-second timeout (kSourceRuleRegexWatchdogTimeout) to prevent catastrophic backtracking from freezing the app. - Non-Core Field Isolation: Non-critical display fields (
coverUrl,intro,kind,status,lastChapter,wordCount) isolate per-field rule errors cleanly so a broken metadata rule never blocks catalog or chapter reading (cancellation andLOGIN_REQUIREDstill propagate).
Background Worker Script Sandbox (QuickJS / JavaScriptCore)
All source JavaScript rules execute off the UI thread inside a dedicated background worker isolate (SourceScriptWorkerHost).
- Isolation & Busy Watchdog: Depending on platform, the worker hosts QuickJS or JavaScriptCore. Foreground reading tasks and background refreshes use separate priority queues. If a script hangs inside a network request or timer callback beyond 30 seconds (
busyWatchdog), the host abandons the stuck worker (up to2concurrent abandoned workers) and spawns a clean replacement—never calling unsafeIsolate.killmid-JavaScriptCore invocation (which would crash the process), and never falling back to running untrusted source scripts on the UI isolate if worker startup fails. - Built-in Host-Accelerated
CryptoJS:globalThis.CryptoJSis preloaded using native host cryptographic primitives forAES,DES,TripleDES(CBC/ECB/CTR), OpenSSLSalted__EVP key derivation,MD5/SHA*/Hmac*, andenc.Utf8/Hex/Base64/Latin1—eliminating multi-kilobyte pure-JS AST parse overhead. - JSON
jsLibLoader:jsLibaccepts either inline JavaScript or a JSON map of library aliases to HTTP(S) script URLs. Remote libraries are cached in a bounded LRU cache (up to 64 scripts, 2 MiB per script, 6 MiB total). Known publiccrypto-jsCDN URLs automatically short-circuit to the built-in acceleratedCryptoJSwithout network fetches.
Supported Global Bindings & Host Bridges
- Top-Level Globals:
java,source,result,book,chapter,baseUrl,src,title,nextChapterUrl,chapters,rssArticle,fromBookInfo,speakText,speakSpeed,cookie,cache, andinfoMap. java.*Bridge Methods:- Network & Browser Interaction:
ajax,ajaxTestAll,get,post,webView,showBrowser,showReadingBrowser,cacheFile,importScript(HTTP(S) URLs only; local filesystem paths are rejected). - Extraction & Chained State:
getString,getStringList,getElements,getElement,setContent(html, url)(updatessrcandbaseUrland returnsjavafor chaining without overwritingresult),setBaseUrl,toURL,put,get,getStrResponse. - Encoding, Crypto & Utilities:
md5Encode,md5Encode16,base64Encode,base64Decode,hexEncodeToString,hexDecodeToString,aes*,des*,tripleDES*,HMacBase64,HMacHex,digestHex,digestBase64Str,timeFormat,timeFormatUTC,t2s,s2t,htmlFormat,toNumChapter,randomUUID,androidId,getWebViewUA,getUserAgent. - Login Forms & Refresh Hooks:
upLoginData(map)(records ordered form updates and persists after action completion;nullresets to source-declared defaults or first option),refreshExplore,searchBook,refreshTocUrl,refreshBookToc.
- Network & Browser Interaction:
cookie.*andcache.*Bridges:cookie.getCookie,setCookie,setWebCookie,getKey,removeCookie,cookieToMap,mapToCookie,replaceCookie, plusresponse.cookies()supporting Java Map methods (.get(),.size(),.containsKey(),{a=1, b=2}.toString()).cache.get,put,getMemory,putMemory,delete, and fresh session snapshot reads viasource.getLoginHeaderMap()/getLoginHeader()(getLoginHeaderMap()returnsnullfor missing, opaque, invalid JSON, arrays, or JSONnull, and an empty map for{}).
Session Journal Replay Across Async Suspensions
Because legacy source scripts expect synchronous java.ajax(...) or java.webView(...) calls, Origo X implements non-blocking async execution through suspension and deterministic journal replay:
- When a script invokes a synchronous network or browser interaction call, the sandbox throws an internal suspension marker. A lightweight tokenizer (
guardNetworkCatchBlocks) rewritescatchblocks across the script so defensivetry { ... } catchwrappers cannot swallow the marker. - The host performs the real HTTP or WebView operation and sends the response back alongside an ordered per-evaluation operation journal (bounded at 65,536 operations and 8 Mi UTF-16 code units).
- On re-execution,
cookie,cache, and explore calls before the suspension point replay their recorded values without repeating side effects; operations after the resume point execute against the refreshed live session state so updated post-login cookies cannot trigger stale pre-login cleanup branches.
Rhino Dialect vs. Standard ES6 Boundary
Older Legado sources occasionally rely on JVM Rhino 1.7.14 extensions that differ from standard ECMAScript enforced by QuickJS and JavaScriptCore:
- Automatically Normalized: The syntax preprocessor rewrites select Rhino patterns into standard ES6, such as unparenthesized arrow destructuring parameters (
arr.map([title, list] => ...)becomes([title, list]) => ...). - Known Boundaries:
- Rhino ES6 mode allows duplicate
letbindings inside functions (function f(x){ let x = x || 1; return x; }), which standard ES6 and JavaScriptCore reject as a syntax error. - Only curated
java.lang,java.util,java.net,java.security, andList.subList/.clearshims are provided—arbitrary JVM class reflection or local file access is intentionally unavailable.
- Rhino ES6 mode allows duplicate
Network Security & SSRF Private-IP Protection
BookSourceNetworkPolicy validates every target host and resolved IP address before opening sockets and across redirects:
- Blocked by Default: Only
http://andhttps://are allowed. Loopback (127.0.0.0/8,::1), link-local (169.254.0.0/16,fe80::/10), multicast, private IPv4 (RFC 1918, CGNAT100.64.0.0/10), IPv4-mapped IPv6, transition addresses (::/96, local NAT6464:ff9b:1::/48, 6to42002::/16, Teredo2001::/32), site-local (fec0::/10), and ULA (fc00::/7) are blocked. - NAT64 & Proxy Fake-IP Rules: Well-known NAT64 (
64:ff9b::/96) unwraps the embedded IPv4 and checks it against public-internet rules. Synthetic DNS Fake-IP pools (198.18.0.0/15,fdfe:dcba:9876::/64) are allowed only for DNS-resolved hostnames when the user explicitly enables proxy/TUN mode—never for literal IP URLs. - Pinned Connections & Limits: Resolved IPs are dialed directly via RFC 8305 Happy Eyeballs (
250 msstagger,12 sconnect budget) to prevent DNS rebinding, responses are capped at8 MiBby default, and channel-synced source restriction and rights-notice policies are enforced before every request.
Server-Side orsp-converter Architecture
For declarative rules that should be exposed as standard ORSP endpoints across readers, deploy or use orsp-legado-adapter.
Endpoints & Supported Declarative Subset
- Converted sources expose standard discovery at
{ORIGIN}/s/<id>/.well-known/open-reading-source.jsonand API routes under{ORIGIN}/s/<id>/api/. - Supports standard Default/CSS selectors, basic and recursive JSONPath, JSON field templates, URL templates, POST forms, charset transcoding, static cookies, and HTTP
Set-Cookieredirect sessions. - By security design, the server adapter does not execute inline JavaScript / Java / Rhino rules, interactive WebView logins, CAPTCHA/bot-challenge bypasses, or the full XPath dialect.
Four-Stage Audit Gate & Cover Proxy
- Deduplication: Sources sharing the same
bookSourceUrldeduplicate automatically onto a single mounted ORSP ID. - Four-Stage Verification: A converted source is published only after passing all four live pipeline checks (
search -> detail -> catalog -> content) under explicit terms and rights confirmation, followed by periodic background re-audits (health probes are excluded from usage stats). - Cover Proxy & Concurrency Caps: Same-origin covers are proxied through the adapter with
Content-Type, byte-size, and redirect checks, backed by a bounded persistent disk cache (24 hfresh TTL,168 hstale fallback,256 MiBmax size). Both upstream fetches and cover proxying enforce global and per-source concurrency limits, returning retryable503responses withRetry-Afterwhen saturated.
See also: Book Sources Guide, Origo Source Overview, ORSP 1.6 Protocol & API Reference, and Source Terms.
Hai trovato un problema in questa guida? Suggerisci una correzione