ドキュメントを見る

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.

このページの内容

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.xxx matches tokenized DOM class names directly—supporting colon-containing Tailwind classes (such as class.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, with odd, 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/@xpath prefixes, 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 Dart RegExp flags while preserving syntax errors on malformed patterns.
  • 2-Second Isolate Watchdog: When an input string reaches 16,384 characters 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 and LOGIN_REQUIRED still 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 to 2 concurrent abandoned workers) and spawns a clean replacement—never calling unsafe Isolate.kill mid-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.CryptoJS is preloaded using native host cryptographic primitives for AES, DES, TripleDES (CBC/ECB/CTR), OpenSSL Salted__ EVP key derivation, MD5/SHA*/Hmac*, and enc.Utf8/Hex/Base64/Latin1—eliminating multi-kilobyte pure-JS AST parse overhead.
  • JSON jsLib Loader: jsLib accepts 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 public crypto-js CDN URLs automatically short-circuit to the built-in accelerated CryptoJS without 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, and infoMap.
  • 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) (updates src and baseUrl and returns java for chaining without overwriting result), 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; null resets to source-declared defaults or first option), refreshExplore, searchBook, refreshTocUrl, refreshBookToc.
  • cookie.* and cache.* Bridges:
    • cookie.getCookie, setCookie, setWebCookie, getKey, removeCookie, cookieToMap, mapToCookie, replaceCookie, plus response.cookies() supporting Java Map methods (.get(), .size(), .containsKey(), {a=1, b=2} .toString()).
    • cache.get, put, getMemory, putMemory, delete, and fresh session snapshot reads via source.getLoginHeaderMap() / getLoginHeader() (getLoginHeaderMap() returns null for missing, opaque, invalid JSON, arrays, or JSON null, 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:

  1. When a script invokes a synchronous network or browser interaction call, the sandbox throws an internal suspension marker. A lightweight tokenizer (guardNetworkCatchBlocks) rewrites catch blocks across the script so defensive try { ... } catch wrappers cannot swallow the marker.
  2. 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).
  3. 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 let bindings 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, and List.subList / .clear shims are provided—arbitrary JVM class reflection or local file access is intentionally unavailable.

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:// and https:// are allowed. Loopback (127.0.0.0/8, ::1), link-local (169.254.0.0/16, fe80::/10), multicast, private IPv4 (RFC 1918, CGNAT 100.64.0.0/10), IPv4-mapped IPv6, transition addresses (::/96, local NAT64 64:ff9b:1::/48, 6to4 2002::/16, Teredo 2001::/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 ms stagger, 12 s connect budget) to prevent DNS rebinding, responses are capped at 8 MiB by 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.json and 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-Cookie redirect 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

  1. Deduplication: Sources sharing the same bookSourceUrl deduplicate automatically onto a single mounted ORSP ID.
  2. 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).
  3. 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 h fresh TTL, 168 h stale fallback, 256 MiB max size). Both upstream fetches and cover proxying enforce global and per-source concurrency limits, returning retryable 503 responses with Retry-After when saturated.

See also: Book Sources Guide, Origo Source Overview, ORSP 1.6 Protocol & API Reference, and Source Terms.

このガイドに問題がありますか? 修正を提案