@ppp0/runtime 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1410 @@
1
+ import { CROSS_PEER_CAPABILITIES, DEFAULT_TIMEOUTS, PppError, applyPppParam, assertFetchableUrl, assertNoSchemeDowngrade, inferFormat, isControlError, isFetchableUrl, isPppError, isResolveErrorCode, normalizeCursor, matureFromRate, normalizePppUri, parsePppUri, pickLetter, isReservedPeerId, riskLevelFor, } from '@ppp0/core';
2
+ import { applyProxyBase, createHppPeer, defaultIsolation, loadPluginFromSource } from '@ppp0/hpp-bridge';
3
+ import { addressCacheKey, addressRate, importTargetOf, letterPage, letterSections, letterUrn, } from './address.js';
4
+ import { CircuitBreaker } from './breaker.js';
5
+ import { ViewCache, effectiveTtl } from './cache.js';
6
+ import { isStaticDoc, parseManifest, parseStaticDoc, resolveUrl } from './manifest.js';
7
+ import { createStaticPeer } from './static.js';
8
+ /** §3.6:单次调用缺省预算 5000ms。 */
9
+ const DEFAULT_RESOLVE_TIMEOUT_MS = 5000;
10
+ /** 文档可声明的镜像上限(与 schema 的 `mirrors.maxItems: 4` 一致,§2.2 / §4.2)。 */
11
+ const MIRROR_LIMIT = 4;
12
+ /**
13
+ * 读取文档顶层 `mirrors`(§2.2 / §4.2):只接受绝对 `https:` 地址,去重、排除自身、最多 4 条。
14
+ *
15
+ * 非法条目(非字符串 / 相对路径 / 非 https scheme / 解析不出 URL)与超出上限的部分
16
+ * **必须忽略并在日志中标注**、不阻断主文档解析;`http:` 条目同样在读取期忽略(§2.2
17
+ * 「`ppp:` / `http:` / `file:` … 必须忽略」),只有留下的 https 镜像才进入回退候选。
18
+ */
19
+ function readMirrors(json, selfUrls, logger) {
20
+ if (!json || typeof json !== 'object' || Array.isArray(json))
21
+ return [];
22
+ const raw = json.mirrors;
23
+ if (!Array.isArray(raw))
24
+ return [];
25
+ const mirrors = [];
26
+ for (let index = 0; index < raw.length; index++) {
27
+ if (mirrors.length >= MIRROR_LIMIT) {
28
+ logger?.(`mirrors[${index}] 超出 ${MIRROR_LIMIT} 条上限,已忽略`);
29
+ continue;
30
+ }
31
+ const entry = raw[index];
32
+ if (typeof entry !== 'string') {
33
+ logger?.(`mirrors[${index}] 不是字符串,已忽略`);
34
+ continue;
35
+ }
36
+ const value = entry.trim();
37
+ if (!/^https:\/\//i.test(value)) {
38
+ logger?.(`mirrors[${index}] 不是绝对 https 地址,已忽略:${stripQuery(value)}`);
39
+ continue;
40
+ }
41
+ try {
42
+ new URL(value);
43
+ }
44
+ catch {
45
+ logger?.(`mirrors[${index}] 不是合法 URL,已忽略:${stripQuery(value)}`);
46
+ continue;
47
+ }
48
+ if (selfUrls.includes(value) || mirrors.includes(value))
49
+ continue;
50
+ mirrors.push(value);
51
+ }
52
+ return mirrors;
53
+ }
54
+ /** 失败 detail / 日志里的地址一律去掉 query(§3.6.3 第 4、7 条:禁止回显 query)。 */
55
+ function stripQuery(url) {
56
+ const at = url.indexOf('?');
57
+ return at < 0 ? url : url.slice(0, at);
58
+ }
59
+ /** §3.3 镜像回退的逐条失败行:地址(无 query)→ 原因(回显的同址 URL 同步去 query)。 */
60
+ function failureLine(candidate, error) {
61
+ const label = stripQuery(candidate);
62
+ const reason = errorMessage(error).split(candidate).join(label);
63
+ return `${label} → ${reason}`;
64
+ }
65
+ export class PppRuntime {
66
+ options;
67
+ now;
68
+ peers = new Map();
69
+ aliases = new Map();
70
+ breakers = new Map();
71
+ cache;
72
+ mediaCache = new Map();
73
+ sourceCache = new Map();
74
+ docCache = new Map();
75
+ /**
76
+ * 文档声明的镜像表(`mirrors`,§2.2 / §4.2),按请求地址与最终地址记忆。
77
+ * 网络失败时文档本身拿不到,只能靠此前成功拉取时学到的这一份来重试(§3.3:
78
+ * 「镜像列表取自该源最近一次成功获取的文档」)。
79
+ */
80
+ mirrorCache = new Map();
81
+ previews = new Map();
82
+ disabled = new Set();
83
+ /**
84
+ * §3.3 步骤 5:≤30s 的同 `(peerId, itemId, episodeId, qn, lang)` 去重与进行中合并。
85
+ * **键必须排除 `token` 与 `h.*` 的值**;解析结果禁止落视图缓存(§6.4)。
86
+ */
87
+ resolveCache = new Map();
88
+ adultEnabled;
89
+ constructor(options = {}) {
90
+ this.options = options;
91
+ this.now = options.now ?? (() => Date.now());
92
+ this.cache = new ViewCache(this.now);
93
+ this.adultEnabled = options.adultEnabled ?? false;
94
+ }
95
+ setAdultEnabled(enabled) {
96
+ this.adultEnabled = enabled;
97
+ }
98
+ get adultMode() {
99
+ return this.adultEnabled;
100
+ }
101
+ listPeers() {
102
+ return [...this.peers.values()];
103
+ }
104
+ getPeer(peerId) {
105
+ const direct = this.peers.get(peerId);
106
+ if (direct)
107
+ return direct;
108
+ const alias = this.aliases.get(peerId);
109
+ const aliased = alias ? this.peers.get(alias) : undefined;
110
+ if (aliased)
111
+ return aliased;
112
+ throw new PppError('NOT_FOUND', `未知 Peer:${peerId}`);
113
+ }
114
+ /** Tests and embedders may register a pre-built adapter. */
115
+ registerPeer(peer, alias) {
116
+ // §2.4 规则 4 / §3.8:`i` 与 `add` 是保留 peerId,归一化后命中的一律拒绝注册
117
+ //(清单条目、静态档 peer.id、手动注册同样适用;别名即清单 entry.id,一并校验)。
118
+ assertNotReservedPeerId(peer.id, 'peerId');
119
+ if (alias !== undefined)
120
+ assertNotReservedPeerId(alias, 'entryId');
121
+ this.peers.set(peer.id, peer);
122
+ this.disabled.delete(peer.id);
123
+ if (alias && alias !== peer.id)
124
+ this.aliases.set(alias, peer.id);
125
+ }
126
+ /** Enable a user source after its explicit confirmation (spec §7.2). */
127
+ enablePeer(peerId) {
128
+ const peer = this.getPeer(peerId);
129
+ this.disabled.delete(peer.id);
130
+ }
131
+ disablePeer(peerId) {
132
+ const peer = this.getPeer(peerId);
133
+ this.disabled.add(peer.id);
134
+ }
135
+ isPeerEnabled(peerId) {
136
+ const peer = this.getPeer(peerId);
137
+ return !this.disabled.has(peer.id);
138
+ }
139
+ /** Effective L1 isolation: 'worker' in browsers, 'none' in Node / native shells. */
140
+ get isolationMode() {
141
+ return this.options.isolation ?? defaultIsolation();
142
+ }
143
+ removePeer(peerId) {
144
+ const peer = this.peers.get(peerId);
145
+ peer?.dispose?.();
146
+ this.peers.delete(peerId);
147
+ this.disabled.delete(peerId);
148
+ for (const [alias, target] of this.aliases) {
149
+ if (target === peerId)
150
+ this.aliases.delete(alias);
151
+ }
152
+ for (const key of this.breakers.keys()) {
153
+ if (key.startsWith(`${peerId}:`))
154
+ this.breakers.delete(key);
155
+ }
156
+ }
157
+ // ───────────────────────── discovery ─────────────────────────
158
+ async fetchText(url, policy = this.egressPolicy()) {
159
+ const fetchImpl = this.options.fetchImpl ?? ((...args) => fetch(...args));
160
+ const { absolute, sameOrigin } = this.resolveTarget(url);
161
+ const trustedOrigin = sameOrigin && this.options.allowSameOrigin !== false;
162
+ if (!trustedOrigin)
163
+ assertFetchableUrl(absolute, policy);
164
+ const target = applyProxyBase(url, this.options.proxyBase);
165
+ const response = await fetchImpl(target);
166
+ if (!response.ok) {
167
+ throw new PppError('NOT_FOUND', `下载失败:HTTP ${response.status} ${url}`, { status: response.status });
168
+ }
169
+ const text = await response.text();
170
+ const finalUrl = unproxyUrl(response.url || target, this.options.proxyBase, absolute);
171
+ if (!trustedOrigin && /^https?:\/\//i.test(finalUrl)) {
172
+ const finalObj = assertFetchableUrl(finalUrl, policy);
173
+ assertNoSchemeDowngrade(new URL(absolute), finalObj);
174
+ }
175
+ return { text, finalUrl };
176
+ }
177
+ /** Relative URLs are only meaningful in a browser; same-origin assets are trusted. */
178
+ resolveTarget(url) {
179
+ const href = globalThis.location?.href;
180
+ let absolute = url;
181
+ if (!/^[a-z][a-z0-9+.-]*:/i.test(url)) {
182
+ if (!href)
183
+ throw new PppError('INVALID_ARGUMENT', `相对 URL 只能在浏览器中使用:${url}`);
184
+ absolute = new URL(url, href).toString();
185
+ }
186
+ const sameOrigin = !!href && new URL(absolute).origin === new URL(href).origin;
187
+ return { absolute, sameOrigin };
188
+ }
189
+ /**
190
+ * Base egress policy for this runtime. `insecure` is the **per-source** plaintext
191
+ * opt-in: it only adds `allowHttp` for that one source's requests and never touches
192
+ * `allowPrivateHosts` (loopback / intranet stay rejected) nor the downgrade check.
193
+ */
194
+ egressPolicy(insecure = false) {
195
+ return {
196
+ allowHttp: this.options.allowHttp === true || insecure === true,
197
+ // §7.5 ruling: the per-source plaintext exemption relaxes the SCHEME only, and it
198
+ // must never be in effect together with `allowPrivateHosts` — so an insecure
199
+ // source always gets an explicit `false` here, whatever the runtime default is.
200
+ allowPrivateHosts: insecure ? false : this.options.allowPrivateHosts,
201
+ allowIpLiterals: this.options.allowIpLiterals,
202
+ };
203
+ }
204
+ /** Policy for one peer's own egress: only a peer explicitly marked `insecure` gets http. */
205
+ policyForPeer(peerId) {
206
+ const peer = this.peers.get(this.aliases.get(peerId) ?? peerId);
207
+ return this.egressPolicy(peer?.insecure === true);
208
+ }
209
+ getPluginSource(url, policy = this.egressPolicy()) {
210
+ let promise = this.sourceCache.get(url);
211
+ if (!promise) {
212
+ promise = this.fetchText(url, policy).then((result) => result.text);
213
+ promise.catch(() => this.sourceCache.delete(url));
214
+ this.sourceCache.set(url, promise);
215
+ }
216
+ return promise;
217
+ }
218
+ async getStaticDoc(url, policy = this.egressPolicy()) {
219
+ const cached = this.docCache.get(url);
220
+ if (cached)
221
+ return cached;
222
+ const { json, documentUrl } = await this.fetchDocument(url, policy, (data, docUrl) => {
223
+ parseStaticDoc(data, docUrl);
224
+ });
225
+ const doc = parseStaticDoc(json, documentUrl);
226
+ this.docCache.set(url, doc);
227
+ return doc;
228
+ }
229
+ /**
230
+ * 拉取一份 JSON 文档(manifest 与 L0 静态档),主地址失败时按文档声明的 `mirrors`
231
+ * 顺序回退(§3.3 镜像回退):主地址 → 镜像 1 → 镜像 2 …(最多 `MIRROR_LIMIT` 条),
232
+ * **第一个成功即采用**。
233
+ *
234
+ * - **触发条件**(§3.3):网络错误 / 超时 / HTTP 非 2xx / 内容非法(非 JSON、形状不符)。
235
+ * 出口策略拒绝(https-only / 主机黑名单 / userinfo / https→http 降级)**不属于**
236
+ * 触发条件:主地址被策略拒绝 → 直接上抛 `INVALID_ARGUMENT`,不得用镜像绕过策略;
237
+ * 镜像被策略拒绝 → 记为该候选失败,继续下一条。
238
+ * - **镜像来源**:进程内 `mirrorCache`(此前成功拉取时从正文学到);内容非法时当场
239
+ * 也能从正文读到镜像表(先记镜像、再做形状校验)。
240
+ * - **同等约束**:每个镜像都走 `fetchText` 的同一套出口策略(https-only、主机黑名单、
241
+ * 拒绝 userinfo、禁止 https→http 降级)。
242
+ * - **全部失败** → `UPSTREAM_ERROR`,`detail` 按候选地址**逐条列出**失败原因
243
+ * (地址与原因中的 URL 均去 query,§3.6.3 第 4、7 条)。
244
+ *
245
+ * 返回 `documentUrl`(成功候选的**最终 URL**,重定向后)与 `mirrorUsed`
246
+ * (主地址成功时为 `null`,否则为实际命中的镜像地址)。
247
+ */
248
+ async fetchDocument(url, policy, validate) {
249
+ const candidates = [];
250
+ const seen = new Set();
251
+ const push = (candidate) => {
252
+ if (candidates.length >= 1 + MIRROR_LIMIT || seen.has(candidate))
253
+ return;
254
+ seen.add(candidate);
255
+ candidates.push(candidate);
256
+ };
257
+ push(url);
258
+ for (const mirror of this.mirrorCache.get(url) ?? [])
259
+ push(mirror);
260
+ const failures = [];
261
+ for (let index = 0; index < candidates.length; index++) {
262
+ const candidate = candidates[index];
263
+ // ── 拉取阶段(网络错误 / 超时 / 5xx / 出口策略) ──
264
+ let text;
265
+ let finalUrl;
266
+ try {
267
+ ({ text, finalUrl } = await this.fetchText(candidate, policy));
268
+ }
269
+ catch (error) {
270
+ // 主地址被出口策略拒绝 → 地址本身不可用,直接上抛(不在 §3.3 触发条件内);
271
+ // 镜像被策略拒绝 → 记为该候选失败,继续下一条。
272
+ if (index === 0 && isPppError(error) && error.code === 'INVALID_ARGUMENT')
273
+ throw error;
274
+ failures.push(failureLine(candidate, error));
275
+ continue;
276
+ }
277
+ // ── 内容阶段(JSON 解析 + 镜像学习 + 形状校验),任一失败换下一个候选 ──
278
+ try {
279
+ const json = parseJson(text, candidate);
280
+ // 先记镜像再做内容校验:内容非法时也要能从正文里读到镜像表(§2.2)。
281
+ const mirrors = readMirrors(json, [candidate, finalUrl, url], this.options.logger);
282
+ if (mirrors.length) {
283
+ this.mirrorCache.set(candidate, mirrors);
284
+ this.mirrorCache.set(finalUrl, mirrors);
285
+ this.mirrorCache.set(url, mirrors);
286
+ for (const mirror of mirrors)
287
+ push(mirror);
288
+ }
289
+ validate(json, finalUrl);
290
+ return { json, documentUrl: finalUrl, mirrorUsed: index === 0 ? null : candidate };
291
+ }
292
+ catch (error) {
293
+ failures.push(failureLine(candidate, error));
294
+ continue;
295
+ }
296
+ }
297
+ // 帮助性归因(不改错误码、不改语义):整批候选里恰有 HTTP 404 失败时,补一句
298
+ // 「条目地址误写成导入」的提示 —— 只是提示,拒绝与否仍由解析层的纯语法规则决定。
299
+ const detail = failures.some((line) => /\bHTTP 404\b/.test(line))
300
+ ? `${failures.join(';')};若这是条目地址,请改用 ppp://<条目字母>/<peerId>/<itemId>(v1.0 裸条目 ppp://<peerId>/<itemId> 已废除),不要写成导入形态 ppp://<导入字母>/<host>/<path>`
301
+ : failures.join(';');
302
+ throw new PppError('UPSTREAM_ERROR', '文档拉取失败:主地址与镜像均不可用', {
303
+ detail,
304
+ });
305
+ }
306
+ /**
307
+ * Fetch a manifest (or L0 doc) and, for HPP entries, load the plugin module to read
308
+ * `meta` (needed for the adult marker). Inspection failures never block preview.
309
+ *
310
+ * `options.allowInsecure` is the per-source plaintext opt-in: it only relaxes the
311
+ * scheme check for THIS preview (loopback / intranet / link-local / single-label
312
+ * hosts are still rejected) and it marks the returned entries `insecure` so the UI
313
+ * can label them 「非加密来源」. Defaults stay https-only.
314
+ *
315
+ * 主地址失败(网络错误 / 5xx / 内容非法)按 §3.3 镜像回退逐条重试,第一个成功即采用;
316
+ * `preview.url` 为实际命中的**最终文档地址**,`preview.mirrorUsed` 仅在走了镜像时给出。
317
+ */
318
+ async preview(url, options = {}) {
319
+ const allowInsecure = options.allowInsecure === true;
320
+ // Kevin 2026-12-05 裁定:**协议层不判门禁**。首段字母只是评级元数据(`rate` / `mature`),
321
+ // 原样交给宿主(播放器 LunaBox 才是门禁的执行方)——不拦、也不因字母拦缓存。
322
+ const rate = addressRate(url);
323
+ // §3.3 步骤 5:以地址为输入的键 = `addressIdentity`,评级字母一个字都不进键——
324
+ // `ppp://k?src=X` / `ppp://l?src=X` / `ppp://s?src=X` 命中同一条缓存(内容相同即共享)。
325
+ const cacheKey = `${allowInsecure ? 'insecure:' : ''}${addressCacheKey(url)}`;
326
+ const cached = this.previews.get(cacheKey);
327
+ if (cached)
328
+ return cached;
329
+ // v1.0:站点只下发导入深链 `ppp://<导入字母>?src=…`(PPP-A-10)——先还原成源地址再去拉取。
330
+ const target = importTargetOf(url) ?? url;
331
+ const { json, documentUrl: finalUrl, mirrorUsed } = await this.fetchDocument(target, this.egressPolicy(allowInsecure), (data, docUrl) => {
332
+ if (isStaticDoc(data))
333
+ parseStaticDoc(data, docUrl);
334
+ else
335
+ parseManifest(data, docUrl);
336
+ });
337
+ /**
338
+ * The document itself travels in plaintext. Same-origin assets go through the
339
+ * `allowSameOrigin` trust path and are never subject to the scheme policy, so the
340
+ * app's own `/my-source.json` (a dev server on http://localhost) is not a
341
+ * plaintext *third-party* source and must not be labelled 「非加密来源」。
342
+ */
343
+ const sourceInsecure = (isHttpUrl(target) || isHttpUrl(finalUrl)) && !this.resolveTarget(target).sameOrigin;
344
+ /** policy for everything this preview fetches (entry documents / plugin sources) */
345
+ const previewPolicy = this.egressPolicy(allowInsecure);
346
+ if (isStaticDoc(json)) {
347
+ const doc = parseStaticDoc(json, finalUrl);
348
+ const riskLevel = riskLevelFor({ mature: doc.peer.mature === true, riskLevel: doc.peer.riskLevel });
349
+ /**
350
+ * Plaintext labelling for an L0 document: the document URL is `http:` **or**
351
+ * the document's own CONTENT carries plaintext playback addresses (`urls[].url`
352
+ * starting with `http://`, or a `next` pointing at an `http:` document) — a
353
+ * fully https document with 55 `http://` streams is still a plaintext source
354
+ * for the user, and the import gate must say so before playback is blocked.
355
+ * Label only: it never widens the egress policy (see `l0ContentInsecure`).
356
+ */
357
+ const insecure = sourceInsecure || allowInsecure || l0ContentInsecure(doc, finalUrl);
358
+ const preview = {
359
+ kind: 'static',
360
+ url: finalUrl,
361
+ name: doc.peer.name,
362
+ description: `ppp-static · ${doc.items.length} 个条目`,
363
+ entries: [
364
+ {
365
+ id: doc.peer.id,
366
+ name: doc.peer.name,
367
+ version: 'static',
368
+ url: finalUrl,
369
+ protocol: 'ppp-static',
370
+ riskLevel,
371
+ priority: 10,
372
+ enabled: true,
373
+ builtin: true,
374
+ activationRequired: false,
375
+ mature: doc.peer.mature === true,
376
+ // Plaintext labelling backfill: the document URL is http, the caller
377
+ // confirmed the per-source `allowInsecure` exemption, or this L0 document's
378
+ // content carries `http://` playback addresses (see `l0ContentInsecure`).
379
+ // At import time the peer's actual `insecure` flag is authoritative.
380
+ insecure,
381
+ },
382
+ ],
383
+ adultRequired: riskLevel === 'gray',
384
+ // 评级元数据照实交宿主:地址首段字母 + 源文档自身的成人声明(协议层不判门禁)。
385
+ mature: riskLevel === 'gray' || matureFromRate(rate),
386
+ insecure,
387
+ };
388
+ if (rate !== null)
389
+ preview.rate = rate;
390
+ if (mirrorUsed)
391
+ preview.mirrorUsed = mirrorUsed;
392
+ this.docCache.set(finalUrl, doc);
393
+ this.previews.set(cacheKey, preview);
394
+ return preview;
395
+ }
396
+ const manifest = parseManifest(json, finalUrl);
397
+ for (const warning of manifest.warnings)
398
+ this.options.logger?.(warning);
399
+ const entries = [];
400
+ for (const plugin of manifest.plugins) {
401
+ const entry = {
402
+ id: plugin.id,
403
+ name: plugin.name,
404
+ version: plugin.version,
405
+ url: plugin.url,
406
+ protocol: plugin.protocol,
407
+ riskLevel: plugin.riskLevel,
408
+ priority: plugin.priority,
409
+ enabled: plugin.enabled,
410
+ builtin: plugin.builtin,
411
+ versionExplicit: plugin.versionExplicit,
412
+ // L0 is the safe tier (no code); L1 user sources need an explicit activation.
413
+ activationRequired: plugin.protocol !== 'ppp-static' && !plugin.builtin,
414
+ };
415
+ if (plugin.description)
416
+ entry.description = plugin.description;
417
+ if (plugin.timeout)
418
+ entry.timeout = plugin.timeout;
419
+ if (plugin.cacheTtlSec)
420
+ entry.cacheTtlSec = plugin.cacheTtlSec;
421
+ // Plaintext labelling: the manifest itself is http, this entry's own URL is, or
422
+ // the caller confirmed the per-source `allowInsecure` opt-in for this preview.
423
+ entry.insecure = sourceInsecure || isHttpUrl(plugin.url) || allowInsecure;
424
+ if (plugin.protocol === 'ppp-static' || /\.json(?:[?#]|$)/i.test(plugin.url)) {
425
+ try {
426
+ const doc = await this.getStaticDoc(plugin.url, previewPolicy);
427
+ entry.protocol = 'ppp-static';
428
+ entry.id = doc.peer.id;
429
+ entry.name = doc.peer.name;
430
+ entry.mature = doc.peer.mature === true;
431
+ entry.activationRequired = false;
432
+ entry.riskLevel = riskLevelFor({ mature: doc.peer.mature === true, riskLevel: doc.peer.riskLevel ?? plugin.riskLevel });
433
+ // L0 content scan: this document is already in hand, so an https L0 entry
434
+ // whose `urls[].url` are `http://` gets the plaintext label too (label only,
435
+ // the entry's egress exemption still comes from the user's confirmation).
436
+ if (l0ContentInsecure(doc, doc.url))
437
+ entry.insecure = true;
438
+ }
439
+ catch (error) {
440
+ entry.inspectError = errorMessage(error);
441
+ }
442
+ }
443
+ else {
444
+ /**
445
+ * v1.0.5 §2.3 / §6.1 协议族三档:`hpp`(第三方 HPP 模块,远程代码安装)**一律 NC-17**,
446
+ * 即使 `meta.mature === false` 也不得放宽(只能收紧);`ppp` 原生插件仍读 `meta.mature`。
447
+ * 反序列化后无法确定协议(缺省 / 未知)按最严处理(同 hpp)。
448
+ * hpp 的判定只看清单里的 `protocol`:插件检查失败也按最严,不能让「加载失败」把评级放回 safe。
449
+ */
450
+ const hppFamily = plugin.protocol !== 'ppp';
451
+ if (hppFamily) {
452
+ entry.mature = true;
453
+ entry.riskLevel = riskLevelFor({ mature: true, riskLevel: plugin.riskLevel });
454
+ }
455
+ try {
456
+ const source = await this.getPluginSource(plugin.url, previewPolicy);
457
+ const mod = await loadPluginFromSource(source, {
458
+ url: plugin.url,
459
+ warn: (message) => this.options.logger?.(message),
460
+ });
461
+ if (!hppFamily) {
462
+ entry.mature = mod.meta.mature === true;
463
+ entry.riskLevel = riskLevelFor({ mature: mod.meta.mature === true, riskLevel: plugin.riskLevel });
464
+ }
465
+ if (mod.meta.version) {
466
+ entry.metaVersion = mod.meta.version;
467
+ if (plugin.versionExplicit && mod.meta.version !== plugin.version) {
468
+ entry.versionMismatch =
469
+ `源 ${plugin.id} 的清单 version(${plugin.version})与插件 meta.version(${mod.meta.version})不一致:请同步两处后再导入`;
470
+ }
471
+ }
472
+ }
473
+ catch (error) {
474
+ entry.inspectError = errorMessage(error);
475
+ }
476
+ }
477
+ entries.push(entry);
478
+ }
479
+ const adultRequired = entries.some((entry) => entry.riskLevel === 'gray');
480
+ // v1.0.5 §3.1 / §6.1:`hpp` 源(含协议无法识别的条目,按最严)的导入字母恒定落在
481
+ // NC-17 类 —— `w` / `x`,子字母仍按 `sha256(源地址) % 2` 确定性选取(§3.1 子字母选择)。
482
+ const hasHppEntry = entries.some((entry) => entry.protocol !== 'ppp' && entry.protocol !== 'ppp-static');
483
+ const previewRate = hasHppEntry ? pickLetter(target, 'import', 'nc17') : rate;
484
+ const preview = {
485
+ kind: 'manifest',
486
+ url: finalUrl,
487
+ name: manifest.name,
488
+ entries,
489
+ adultRequired,
490
+ // 评级元数据照实交宿主:地址首段字母 + 清单里各条目的成人声明(协议层不判门禁)。
491
+ mature: adultRequired || matureFromRate(previewRate),
492
+ insecure: sourceInsecure || allowInsecure,
493
+ };
494
+ if (previewRate !== null)
495
+ preview.rate = previewRate;
496
+ if (manifest.description)
497
+ preview.description = manifest.description;
498
+ if (manifest.pppVersion)
499
+ preview.pppVersion = manifest.pppVersion;
500
+ if (mirrorUsed)
501
+ preview.mirrorUsed = mirrorUsed;
502
+ this.previews.set(cacheKey, preview);
503
+ return preview;
504
+ }
505
+ async import(previewOrUrl, selectedIds, options = {}) {
506
+ // Per-source plaintext opt-in: only the peers imported by THIS call are marked.
507
+ const allowInsecure = options.allowInsecure === true;
508
+ const preview = typeof previewOrUrl === 'string' ? await this.preview(previewOrUrl, { allowInsecure }) : previewOrUrl;
509
+ if (options.adultEnabled !== undefined)
510
+ this.adultEnabled = options.adultEnabled;
511
+ const wanted = selectedIds ? new Set(selectedIds) : null;
512
+ const imported = [];
513
+ for (const entry of preview.entries) {
514
+ if (wanted && !wanted.has(entry.id) && !wanted.has(entry.url))
515
+ continue;
516
+ if (entry.versionMismatch) {
517
+ throw new PppError('UNSUPPORTED', entry.versionMismatch);
518
+ }
519
+ if (entry.riskLevel === 'forbidden') {
520
+ throw new PppError('FORBIDDEN', `源 ${entry.name} 已被拉黑,禁止导入`);
521
+ }
522
+ if (entry.riskLevel === 'gray' && !this.adultEnabled) {
523
+ throw new PppError('ADULT_CONFIRMATION_REQUIRED', `源 ${entry.name} 含成人内容,需显式二次确认`);
524
+ }
525
+ if (!entry.enabled)
526
+ continue;
527
+ const peer = entry.protocol === 'ppp-static'
528
+ ? await this.createStatic(entry, allowInsecure)
529
+ : await this.createHpp(entry, allowInsecure);
530
+ this.registerPeer(peer, entry.id);
531
+ // User sources start disabled until the UI's explicit activation (spec §7.2).
532
+ if (entry.activationRequired === true && options.confirmActivation !== true) {
533
+ this.disabled.add(peer.id);
534
+ }
535
+ imported.push(peer);
536
+ }
537
+ if (!imported.length)
538
+ throw new PppError('NOT_FOUND', '没有导入任何源');
539
+ return imported;
540
+ }
541
+ async createHpp(entry, insecure) {
542
+ // Per-source policy: only `allowHttp` is added, never `allowPrivateHosts`.
543
+ const policy = this.egressPolicy(insecure);
544
+ const source = await this.getPluginSource(entry.url, policy);
545
+ const host = {
546
+ fetchImpl: this.options.fetchImpl,
547
+ proxyBase: this.options.proxyBase,
548
+ storage: this.options.pluginStorage,
549
+ policy,
550
+ now: this.now,
551
+ };
552
+ return createHppPeer({
553
+ source,
554
+ url: entry.url,
555
+ riskLevel: entry.riskLevel,
556
+ priority: entry.priority,
557
+ declaredTtlSec: entry.cacheTtlSec,
558
+ host,
559
+ insecure,
560
+ isolation: this.options.isolation,
561
+ expectedVersion: entry.versionExplicit ? entry.version : undefined,
562
+ logger: this.options.logger,
563
+ timeouts: { ...DEFAULT_TIMEOUTS, ...(this.options.defaultTimeouts ?? {}), ...(entry.timeout ?? {}) },
564
+ codecs: this.options.codecs,
565
+ now: this.now,
566
+ });
567
+ }
568
+ async createStatic(entry, insecure) {
569
+ // Per-source policy: only `allowHttp` is added, never `allowPrivateHosts`.
570
+ const policy = this.egressPolicy(insecure);
571
+ const doc = this.docCache.get(entry.url) ?? (await this.getStaticDoc(entry.url, policy));
572
+ return createStaticPeer(doc, {
573
+ url: entry.url,
574
+ riskLevel: entry.riskLevel,
575
+ priority: entry.priority,
576
+ declaredTtlSec: entry.cacheTtlSec,
577
+ fetchImpl: this.options.fetchImpl,
578
+ headers: this.options.proxyBase ? undefined : undefined,
579
+ policy,
580
+ insecure,
581
+ logger: this.options.logger,
582
+ });
583
+ }
584
+ // ───────────────────────── scheduling ─────────────────────────
585
+ breakerFor(peerId, capability) {
586
+ const key = `${peerId}:${capability}`;
587
+ let breaker = this.breakers.get(key);
588
+ if (!breaker) {
589
+ breaker = new CircuitBreaker({ ...this.options.breaker, now: this.now });
590
+ this.breakers.set(key, breaker);
591
+ }
592
+ return breaker;
593
+ }
594
+ eligiblePeers(capability, peerId) {
595
+ const list = peerId ? [this.getPeer(peerId)] : this.listPeers();
596
+ return list
597
+ .filter((peer) => !this.disabled.has(peer.id))
598
+ .filter((peer) => peer.riskLevel !== 'forbidden')
599
+ .filter((peer) => peer.riskLevel !== 'gray' || this.adultEnabled)
600
+ .filter((peer) => peer.has(capability))
601
+ .sort((a, b) => b.priority - a.priority);
602
+ }
603
+ cacheKey(capability, peerId, params) {
604
+ return `${capability}:${peerId}:${stableStringify(params)}`;
605
+ }
606
+ async execute(peer, capability, run, cacheParams) {
607
+ const key = cacheParams !== undefined ? this.cacheKey(capability, peer.id, cacheParams) : null;
608
+ if (key) {
609
+ const hit = this.cache.get(key);
610
+ if (hit !== undefined)
611
+ return hit;
612
+ }
613
+ const breaker = this.breakerFor(peer.id, capability);
614
+ if (!breaker.canRequest()) {
615
+ // C4: 熔断打开统一走规范码 UPSTREAM_ERROR(调用方只认 HPP 定义的码),
616
+ // 并在 cause 里带上 circuitOpen: true 供 UI 区分“已熔断”与“上游真失败”。
617
+ throw new PppError('UPSTREAM_ERROR', `源 ${peer.name} 的 ${capability} 已熔断,稍后重试`, {
618
+ cause: { circuitOpen: true },
619
+ });
620
+ }
621
+ try {
622
+ const value = await run();
623
+ breaker.onSuccess();
624
+ if (key) {
625
+ const ttl = effectiveTtl(capability, this.options.cacheTtlSec, peer.declaredTtlSec);
626
+ this.cache.set(key, value, ttl);
627
+ }
628
+ return value;
629
+ }
630
+ catch (error) {
631
+ // CANCELLED 仍是控制信号:用户主动取消不算上游故障,不计熔断、不跨 Peer 重试。
632
+ // H1:TIMEOUT 计入熔断失败 —— 上游持续超时必须能把熔断打开;两者都原样上抛。
633
+ const timeout = isPppError(error) && error.code === 'TIMEOUT';
634
+ if (!isControlError(error) || timeout)
635
+ breaker.onFailure();
636
+ throw error;
637
+ }
638
+ }
639
+ async dispatchQuery(capability, run, cacheParams, peerId) {
640
+ const peers = this.eligiblePeers(capability, peerId);
641
+ if (!peers.length)
642
+ throw new PppError('NOT_FOUND', `没有支持 ${capability} 的源`);
643
+ let lastError = null;
644
+ for (const peer of peers) {
645
+ try {
646
+ const value = await this.execute(peer, capability, () => run(peer), cacheParams);
647
+ return { peerId: peer.id, value };
648
+ }
649
+ catch (error) {
650
+ if (isControlError(error))
651
+ throw error;
652
+ lastError = error;
653
+ this.options.logger?.(`${capability} 在 ${peer.id} 失败`, error);
654
+ }
655
+ }
656
+ throw isPppError(lastError)
657
+ ? lastError
658
+ : new PppError('UPSTREAM_ERROR', `${capability} 在所有源上失败`, { cause: lastError });
659
+ }
660
+ // ───────────────────────── public capabilities ─────────────────────────
661
+ async home(options = {}) {
662
+ const { peerId, value } = await this.dispatchQuery('home', (peer) => peer.home(), {}, options.peerId);
663
+ // v1.0:core 归一化产出的裸 urn 就地改写成带评级字母的条目地址
664
+ return { peerId, sections: letterSections(value) };
665
+ }
666
+ async listSection(sectionId, cursor = null, options = {}) {
667
+ const { peerId, value } = await this.dispatchQuery('home', (peer) => peer.listSection(sectionId, normalizeCursor(cursor)), { sectionId, cursor }, options.peerId);
668
+ const peer = this.getPeer(peerId);
669
+ return { peerId, page: letterPage(value), localSearch: peer.localSearch === true };
670
+ }
671
+ async feed(cursor = null, options = {}) {
672
+ const { peerId, value } = await this.dispatchQuery('feed', (peer) => peer.feed(normalizeCursor(cursor)), { cursor }, options.peerId);
673
+ return { peerId, page: letterPage(value), localSearch: this.getPeer(peerId).localSearch === true };
674
+ }
675
+ async categories(options = {}) {
676
+ const { peerId, value } = await this.dispatchQuery('catalog', (peer) => peer.categories(), {}, options.peerId);
677
+ return { peerId, categories: value };
678
+ }
679
+ async catalog(params = {}) {
680
+ const categoryId = params.categoryId ?? 'all';
681
+ const cursor = normalizeCursor(params.cursor ?? null);
682
+ const { peerId, value } = await this.dispatchQuery('catalog', (peer) => peer.catalog(categoryId, params.sort, cursor), { categoryId, sort: params.sort ?? null, cursor }, params.peerId);
683
+ return { peerId, page: letterPage(value), localSearch: this.getPeer(peerId).localSearch === true };
684
+ }
685
+ async search(query, options = {}) {
686
+ const needle = query.trim();
687
+ if (!needle)
688
+ return { peerId: null, items: [], next: null, localSearch: false };
689
+ if (options.peerId) {
690
+ const peer = this.getPeer(options.peerId);
691
+ const page = await this.execute(peer, 'search', () => peer.search(needle, normalizeCursor(options.cursor ?? null)), {
692
+ query: needle,
693
+ cursor: options.cursor ?? null,
694
+ });
695
+ letterPage(page);
696
+ const scope = localSearchScope([peer]);
697
+ return { peerId: peer.id, items: page.items, next: page.next, localSearch: peer.localSearch === true, ...scope };
698
+ }
699
+ const peers = this.eligiblePeers('search');
700
+ const remote = peers.filter((peer) => !peer.localSearch);
701
+ const local = peers.filter((peer) => peer.localSearch);
702
+ let lastError = null;
703
+ for (const peer of remote) {
704
+ try {
705
+ const page = await this.execute(peer, 'search', () => peer.search(needle, null), { query: needle, cursor: null });
706
+ letterPage(page);
707
+ return { peerId: peer.id, items: page.items, next: page.next, localSearch: false };
708
+ }
709
+ catch (error) {
710
+ if (isControlError(error))
711
+ throw error;
712
+ lastError = error;
713
+ }
714
+ }
715
+ // L0 has no search endpoint: substring-scan the loaded items instead.
716
+ const seen = new Set();
717
+ const merged = [];
718
+ let localPeerId = null;
719
+ for (const peer of local) {
720
+ try {
721
+ const page = await this.execute(peer, 'search', () => peer.search(needle, null), { query: needle, cursor: null });
722
+ letterPage(page);
723
+ localPeerId = peer.id;
724
+ for (const item of page.items) {
725
+ if (seen.has(item.urn))
726
+ continue;
727
+ seen.add(item.urn);
728
+ merged.push(item);
729
+ }
730
+ }
731
+ catch (error) {
732
+ if (isControlError(error))
733
+ throw error;
734
+ lastError = error;
735
+ }
736
+ }
737
+ if (local.length) {
738
+ return {
739
+ peerId: localPeerId,
740
+ items: merged,
741
+ next: null,
742
+ localSearch: true,
743
+ ...localSearchScope(local),
744
+ };
745
+ }
746
+ if (lastError)
747
+ throw lastError;
748
+ throw new PppError('NOT_FOUND', `没有支持搜索的源`);
749
+ }
750
+ /** Strictly peer-bound: item ids are only unique inside their peer. */
751
+ async detail(address) {
752
+ const target = addressOf(address);
753
+ const peer = this.getPeer(target.peerId);
754
+ if (!peer.detail)
755
+ throw new PppError('UNSUPPORTED', `源 ${peer.name} 不支持详情`);
756
+ const detail = await this.execute(peer, 'detail', () => peer.detail(target.itemId), {
757
+ itemId: target.itemId,
758
+ // §3.3 步骤 5 / Kevin 2026-12-05:身份键去评级——`i` ≡ `j` ≡ `q` 同键(内容相同即共享)
759
+ });
760
+ return letterUrn(detail);
761
+ }
762
+ /** Strictly peer-bound; never retried on another peer. */
763
+ async playback(address) {
764
+ const target = addressOf(address, true);
765
+ const peer = this.getPeer(target.peerId);
766
+ if (!peer.playback)
767
+ throw new PppError('UNSUPPORTED', `源 ${peer.name} 不支持播放`);
768
+ let episodeId = target.episodeId;
769
+ if (!episodeId) {
770
+ const detail = await this.detail({ peerId: target.peerId, itemId: target.itemId });
771
+ const first = detail.playlists[0]?.episodes[0];
772
+ if (!first)
773
+ throw new PppError('NOT_FOUND', '该条目没有分集');
774
+ episodeId = first.id;
775
+ }
776
+ const codecs = this.resolveCodecs();
777
+ const dedupeMs = this.options.mediaDedupeMs ?? 30_000;
778
+ // §3.3 步骤 5 / Kevin 2026-12-05:去重键**去评级**——`i` ≡ `j` ≡ `q` 同键(内容相同即共享);
779
+ // token / h.* 永不入键。评级只作为元数据随结果返回,不参与任何键。
780
+ const key = `${target.peerId}/${target.itemId}/${episodeId}/${codecs.join(',')}`;
781
+ const cached = this.mediaCache.get(key);
782
+ if (cached && this.now() - cached.at < dedupeMs)
783
+ return cached.promise;
784
+ const promise = this.execute(peer, 'media', () => peer.playback(target.itemId, episodeId, codecs)).then((playback) => this.assertPlayableStreams(playback, target.peerId));
785
+ this.mediaCache.set(key, { at: this.now(), promise });
786
+ promise.catch(() => this.mediaCache.delete(key));
787
+ return promise;
788
+ }
789
+ /**
790
+ * Last gate before a stream URL reaches the player: a source must not be able to hand
791
+ * us `file:` / `javascript:` / intranet URLs (they would run with the player's trust).
792
+ */
793
+ assertPlayableStreams(playback, peerId) {
794
+ // Per-peer policy: only a peer the user explicitly marked `insecure` may hand us
795
+ // a plaintext stream URL; every other peer keeps the https-only default.
796
+ const policy = this.policyForPeer(peerId);
797
+ const streams = playback.streams.filter((stream) => {
798
+ const ok = isFetchableUrl(stream.url, policy);
799
+ if (!ok)
800
+ this.options.logger?.(`丢弃不可信的播放地址(${peerId})`, stream.url);
801
+ return ok;
802
+ });
803
+ if (!streams.length) {
804
+ throw new PppError('UPSTREAM_CHANGED', `源 ${peerId} 没有可安全播放的地址`);
805
+ }
806
+ const out = { streams };
807
+ if (playback.durationSec)
808
+ out.durationSec = playback.durationSec;
809
+ return out;
810
+ }
811
+ async comments(mediaId, episodeId, options) {
812
+ const peer = this.getPeer(options.peerId);
813
+ if (!peer.comments)
814
+ throw new PppError('UNSUPPORTED', `源 ${peer.name} 不支持评论`);
815
+ return this.execute(peer, 'comments', () => peer.comments(mediaId, episodeId, normalizeCursor(options.cursor ?? null)), { mediaId, episodeId, cursor: options.cursor ?? null });
816
+ }
817
+ async endpoints(peerId) {
818
+ return this.getPeer(peerId).endpoints ?? [];
819
+ }
820
+ setEndpoint(peerId, endpointId) {
821
+ const peer = this.getPeer(peerId);
822
+ if (!peer.setEndpoint)
823
+ throw new PppError('UNSUPPORTED', '该源没有线路概念');
824
+ peer.setEndpoint(endpointId);
825
+ }
826
+ async resolveCover(peerId, image) {
827
+ const peer = this.getPeer(peerId);
828
+ if (!peer.resolveCover)
829
+ return typeof image === 'string' ? image : image?.url;
830
+ return peer.resolveCover(image);
831
+ }
832
+ // ───────────────────────── resolve(§3.3 / §3.6) ─────────────────────────
833
+ /**
834
+ * Resolver(§3.6):`ppp://` 地址 → 归一化 `streams[]`,只返回地址、不代拉媒体流。
835
+ *
836
+ * 步骤严格按 §3.3:归一化 → 找 peer(缺失 UNKNOWN_PEER)→ 停用/风险 PEER_DISABLED →
837
+ * 熔断打开 PEER_NOT_LOADED → L0/L1 文档查找(ITEM_NOT_FOUND / EPISODE_NOT_FOUND)→
838
+ * 调 `media.resolvePlayback`(透传 qn/token/lang)→ 出口策略过滤(allowHttp、回环/
839
+ * 内网拒)→ 空则 NO_STREAMS。
840
+ *
841
+ * 失败以 `{ ok: false, error: { code, ... } }` 返回(§3.6「禁止抛业务异常」);唯一
842
+ * 抛出的异常是 `options.signal` 已中止时的 `CANCELLED`(§3.6 唯一例外)。
843
+ * `token` 绝不写日志、绝不进缓存键、绝不回显在返回体 `uri` 中。
844
+ */
845
+ async resolve(input, options = {}) {
846
+ const startedAt = this.now();
847
+ if (options.signal?.aborted)
848
+ throw new PppError('CANCELLED', '解析已被取消');
849
+ const uri = typeof input === 'string' ? input : input?.uri;
850
+ let plan;
851
+ try {
852
+ plan = buildResolvePlan(typeof uri === 'string' ? uri : '', [
853
+ options,
854
+ typeof input === 'object' && input ? input.overrides : undefined,
855
+ ]);
856
+ }
857
+ catch (error) {
858
+ // 解析期错误(INVALID_URI / BAD_PARAM)同样以失败信封返回,不抛业务异常。
859
+ return resolveFailure(error, startedAt);
860
+ }
861
+ // 门禁必须先于缓存 / 合并判定(§3.3 步骤 5 末条):注册表三态 + NC-17 字母(§7.1)
862
+ // 在命中去重缓存之前就判完,禁止因缓存 / 合并而放宽。
863
+ try {
864
+ this.assertResolvable(plan);
865
+ }
866
+ catch (error) {
867
+ return resolveFailure(error, startedAt, plan);
868
+ }
869
+ const dedupeMs = this.options.mediaDedupeMs ?? 30_000;
870
+ if (options.bypassDedup === true)
871
+ return this.runResolve(plan, options, startedAt);
872
+ const cached = this.resolveCache.get(plan.cacheKey);
873
+ if (cached) {
874
+ if (startedAt - cached.at < dedupeMs)
875
+ return cached.promise;
876
+ this.resolveCache.delete(plan.cacheKey);
877
+ }
878
+ const promise = this.runResolve(plan, options, startedAt);
879
+ this.resolveCache.set(plan.cacheKey, { at: startedAt, promise });
880
+ const drop = () => {
881
+ const current = this.resolveCache.get(plan.cacheKey);
882
+ if (current && current.promise === promise)
883
+ this.resolveCache.delete(plan.cacheKey);
884
+ };
885
+ // 失败结果不保留(去重只对成功结果生效);CANCELLED 造成的 reject 同样清理。
886
+ promise.then((result) => {
887
+ if (!result.ok)
888
+ drop();
889
+ }, drop);
890
+ return promise;
891
+ }
892
+ async runResolve(plan, options, startedAt) {
893
+ const deadline = options.deadline ?? startedAt + (options.timeoutMs ?? DEFAULT_RESOLVE_TIMEOUT_MS);
894
+ try {
895
+ if (this.now() >= deadline)
896
+ throw new PppError('TIMEOUT', '解析预算已耗尽');
897
+ return await this.settleBudget(this.resolveCore(plan, options), deadline, options.signal);
898
+ }
899
+ catch (error) {
900
+ // §3.6 唯一抛出的异常是 signal 中止的 CANCELLED;TIMEOUT 走失败信封(HTTP 504)。
901
+ if (isPppError(error) && error.code === 'CANCELLED')
902
+ throw error;
903
+ return resolveFailure(error, startedAt, plan);
904
+ }
905
+ }
906
+ /** 兜底硬超时 + 取消:主路径仍是把预算下发给插件(§5.8 / §6.5)。 */
907
+ async settleBudget(work, deadline, signal) {
908
+ void work.catch(() => undefined); // race 落败方的迟到 reject 不得成为 unhandled
909
+ let timer;
910
+ let removeAbort;
911
+ const guard = [
912
+ new Promise((_, reject) => {
913
+ timer = setTimeout(() => reject(new PppError('TIMEOUT', '解析预算耗尽')), Math.max(0, deadline - this.now()));
914
+ timer.unref?.();
915
+ }),
916
+ ];
917
+ if (signal) {
918
+ guard.push(new Promise((_, reject) => {
919
+ const fail = () => reject(new PppError('CANCELLED', '解析已被取消'));
920
+ if (signal.aborted) {
921
+ fail();
922
+ return;
923
+ }
924
+ signal.addEventListener('abort', fail, { once: true });
925
+ removeAbort = () => signal.removeEventListener('abort', fail);
926
+ }));
927
+ }
928
+ try {
929
+ return await Promise.race([work, ...guard]);
930
+ }
931
+ finally {
932
+ if (timer)
933
+ clearTimeout(timer);
934
+ removeAbort?.();
935
+ }
936
+ }
937
+ async resolveCore(plan, options) {
938
+ // ── 步骤 0:注册表匹配与三态(§3.3,确定性,禁止静默降级) ──
939
+ const peer = this.assertResolvable(plan);
940
+ // ── L0 文档 / L1 getDetail 查找(§3.3 步骤 2.1、3.2) ──
941
+ let detail;
942
+ try {
943
+ detail = letterUrn(await this.execute(peer, 'detail', () => peer.detail(plan.itemId), {
944
+ itemId: plan.itemId,
945
+ // §3.3 步骤 5:身份键去评级(Kevin 2026-12-05 裁定)
946
+ }));
947
+ }
948
+ catch (error) {
949
+ throw mapResolveError(error, 'item');
950
+ }
951
+ const located = pickEpisode(plan, detail);
952
+ // ── 解析:media.resolvePlayback(v0.3 扩展入参 qn/token/lang,§3.3 步骤 3.3) ──
953
+ let playback;
954
+ try {
955
+ playback = await this.execute(peer, 'media', () => peer.playback(plan.itemId, located.id, this.resolveCodecs(), {
956
+ qn: plan.params.qn,
957
+ token: plan.params.token,
958
+ lang: plan.params.lang,
959
+ }));
960
+ }
961
+ catch (error) {
962
+ throw mapResolveError(error, 'episode');
963
+ }
964
+ if (!playback?.streams?.length) {
965
+ throw new PppError('UPSTREAM_CHANGED', `源 ${peer.id} 未返回可播放地址`, {
966
+ detail: 'streams 为空或结构不符(§5.9 / §6.7)',
967
+ });
968
+ }
969
+ // ── 出口策略(§7.5 / §3.6.3):allowHttp 未打开时丢 http,回环/内网一律拒 ──
970
+ const basePolicy = this.policyForPeer(peer.id);
971
+ const policy = { ...basePolicy, allowHttp: options.allowHttp ?? basePolicy.allowHttp };
972
+ const kept = playback.streams.filter((stream) => isFetchableUrl(stream.url, policy));
973
+ if (!kept.length) {
974
+ // 结构合法但被出口策略 / allowHttp 过滤干净 → NO_STREAMS(§3.7,不计熔断)
975
+ throw new PppError('NO_STREAMS', '全部地址被出口策略 / allowHttp 过滤', {
976
+ detail: `过滤前 ${playback.streams.length} 条,过滤后 0 条`,
977
+ });
978
+ }
979
+ const streams = kept.map((stream, index) => toResolvedStream(stream, index, plan.params));
980
+ const result = {
981
+ ok: true,
982
+ uri: plan.uri,
983
+ // 评级元数据照实交宿主(单一口径 `rate`;协议层不判门禁、不拦缓存)
984
+ rate: plan.rate,
985
+ mature: matureFromRate(plan.rate),
986
+ peerId: peer.id,
987
+ peerName: peer.name,
988
+ itemId: plan.itemId,
989
+ episodeId: located.id,
990
+ level: peer.protocol === 'ppp-static' ? 'L0' : 'L1',
991
+ item: detail,
992
+ streams,
993
+ ignoredParams: plan.ignoredParams,
994
+ appliedParams: appliedParamsOf(plan.params),
995
+ resolvedAt: this.now(),
996
+ };
997
+ const durationSec = playback.durationSec ?? located.episode?.durationSec;
998
+ if (durationSec !== undefined)
999
+ result.durationSec = durationSec;
1000
+ return result;
1001
+ }
1002
+ /**
1003
+ * §3.3 步骤 0 的**门禁**:注册表匹配(UNKNOWN_PEER)→ 停用 / 拉黑 / 成人(PEER_DISABLED)→
1004
+ * 熔断(PEER_NOT_LOADED)→ 能力(UPSTREAM_ERROR),确定性、禁止静默降级。
1005
+ *
1006
+ * - `resolve()` 在**命中去重缓存之前**先调一次(§3.3 步骤 5 末条:注册表状态不得因缓存 / 合并而放宽);
1007
+ * `resolveCore` 内再调一次(`bypassDedup` 路径同样要过门禁)。
1008
+ * - **Kevin 2026-12-05 裁定:地址里的评级字母不再在此拦人**——`u` / `v` / `w` / `x` 只是
1009
+ * 随结果如实上交的 `rate` / `mature` 元数据,成人门禁是播放器(LunaBox)的事;
1010
+ * 这里只看**注册表状态**(停用 / 拉黑 / 源自身登记为成人且成人开关未开)。
1011
+ */
1012
+ assertResolvable(plan) {
1013
+ const peer = this.lookupPeer(plan.peerId);
1014
+ if (!peer) {
1015
+ throw new PppError('UNKNOWN_PEER', `未注册的源:${plan.peerId}`, {
1016
+ detail: 'peerId 归一化后不在注册表(§3.3 步骤 0)',
1017
+ });
1018
+ }
1019
+ if (this.disabled.has(peer.id) ||
1020
+ peer.riskLevel === 'forbidden' ||
1021
+ (peer.riskLevel === 'gray' && !this.adultEnabled)) {
1022
+ throw new PppError('PEER_DISABLED', `源 ${peer.name} 已停用或需要成人开关`, {
1023
+ detail: 'enabled=false / riskLevel=forbidden / 成人开关未开(§3.3 步骤 0)',
1024
+ });
1025
+ }
1026
+ if (this.breakerFor(peer.id, 'detail').state === 'open' || this.breakerFor(peer.id, 'media').state === 'open') {
1027
+ throw new PppError('PEER_NOT_LOADED', `源 ${peer.name} 未就绪(熔断打开)`, {
1028
+ detail: 'circuit-open(§3.7 PEER_NOT_LOADED)',
1029
+ });
1030
+ }
1031
+ if (!peer.has('detail') || !peer.has('media')) {
1032
+ throw new PppError('UPSTREAM_ERROR', `源 ${peer.name} 不支持 detail/media 能力`, {
1033
+ detail: 'capability-missing(映射见 §5.12 → §3.7)',
1034
+ });
1035
+ }
1036
+ return peer;
1037
+ }
1038
+ lookupPeer(peerId) {
1039
+ const direct = this.peers.get(peerId);
1040
+ if (direct)
1041
+ return direct;
1042
+ const alias = this.aliases.get(peerId);
1043
+ return alias ? this.peers.get(alias) : undefined;
1044
+ }
1045
+ resolveCodecs() {
1046
+ const value = this.options.codecs;
1047
+ if (typeof value === 'function')
1048
+ return value();
1049
+ return value ?? [];
1050
+ }
1051
+ breakerSnapshot(peerId, capability) {
1052
+ return this.breakers.get(`${peerId}:${capability}`)?.snapshot();
1053
+ }
1054
+ clearCache() {
1055
+ this.cache.clear();
1056
+ }
1057
+ }
1058
+ function addressOf(address, withEpisode = false) {
1059
+ if (typeof address === 'string') {
1060
+ // v1.0:首段必须是条目字母(`a b e f i j m n q r u v`);
1061
+ // 裸地址 `ppp://<peerId>/<itemId>` 与其它非法形态一律 INVALID_URI(无兼容层)。
1062
+ const parsed = parsePppUri(address);
1063
+ const target = { peerId: parsed.peerId, itemId: parsed.itemId };
1064
+ if (withEpisode && parsed.episodeId !== undefined)
1065
+ target.episodeId = parsed.episodeId;
1066
+ return target;
1067
+ }
1068
+ if (!address || !address.peerId || !address.itemId) {
1069
+ throw new PppError('INVALID_ARGUMENT', '缺少 peerId / itemId');
1070
+ }
1071
+ // 对象入参没有地址、也就没有字母 → 不参与评级(键里没有任何评级分量)。
1072
+ return { ...address };
1073
+ }
1074
+ function parseJson(text, url) {
1075
+ try {
1076
+ return JSON.parse(text);
1077
+ }
1078
+ catch {
1079
+ throw new PppError('UPSTREAM_CHANGED', `清单不是合法 JSON:${url}`);
1080
+ }
1081
+ }
1082
+ function stableStringify(value) {
1083
+ if (value === null || typeof value !== 'object')
1084
+ return JSON.stringify(value) ?? 'null';
1085
+ if (Array.isArray(value))
1086
+ return `[${value.map(stableStringify).join(',')}]`;
1087
+ const entries = Object.keys(value)
1088
+ .sort()
1089
+ .map((key) => `${JSON.stringify(key)}:${stableStringify(value[key])}`);
1090
+ return `{${entries.join(',')}}`;
1091
+ }
1092
+ function unproxyUrl(responseUrl, proxyBase, originalUrl) {
1093
+ // The dev proxy embeds the upstream in the path; fetch() cannot tell us where a
1094
+ // server-side redirect went, so relative URLs resolve against the original URL.
1095
+ if (responseUrl.includes('/ppp-proxy/') && /^https?:\/\//i.test(originalUrl))
1096
+ return originalUrl;
1097
+ // A function proxyBase points at an arbitrary gateway (LunaBox's local Rust `/p?u=…&t=…`
1098
+ // route). The gateway follows upstream redirects server-side, so `response.url` is the
1099
+ // gateway URL — treating it as the final address would both resolve relative URLs against
1100
+ // `http://127.0.0.1` and trip assertNoSchemeDowngrade (https → the gateway's http).
1101
+ if (typeof proxyBase === 'function' && /^https?:\/\//i.test(originalUrl))
1102
+ return originalUrl;
1103
+ return responseUrl || originalUrl;
1104
+ }
1105
+ function errorMessage(error) {
1106
+ if (error instanceof Error)
1107
+ return error.message;
1108
+ return String(error);
1109
+ }
1110
+ /** 保留 peerId(单字母 a–z + 历史保留字 `add` / `import`)拒绝:注册表永不容纳它们(§2.4 规则 4 / §3.8 / PPP-A-12)。 */
1111
+ function assertNotReservedPeerId(id, field) {
1112
+ if (!isReservedPeerId(id))
1113
+ return;
1114
+ const normalized = id.toLowerCase().replace(/[^a-z0-9._-]/g, '-');
1115
+ throw new PppError('INVALID_ARGUMENT', `保留 peerId「${normalized}」禁止注册(§2.4 规则 4 / §3.8)`, {
1116
+ detail: `${field}=${id} 归一化后为保留命名空间 ${normalized}(单字母 a–z 与 add / import 永不注册为普通 Peer)`,
1117
+ });
1118
+ }
1119
+ /** True only for a literal `http:` URL (plaintext egress → must be labelled). */
1120
+ function isHttpUrl(url) {
1121
+ return /^http:\/\//i.test(url.trim());
1122
+ }
1123
+ /**
1124
+ * Sampling caps for the L0 plaintext-content scan: an oversized source must never
1125
+ * stall a preview, so the walk stops at 500 items / 2000 urls (and returns on the
1126
+ * first hit). Anything beyond the sample is simply not looked at.
1127
+ */
1128
+ const L0_SCAN_MAX_ITEMS = 500;
1129
+ const L0_SCAN_MAX_URLS = 2000;
1130
+ const L0_SCAN_MAX_DEPTH = 16;
1131
+ /**
1132
+ * Content-level plaintext detection for an **L0 (`ppp-static`) document** whose URL may
1133
+ * well be https: `true` when any `urls[].url` starts with `http://` (item → playlists →
1134
+ * episodes → urls, item → episodes → urls, …) or when `next` resolves to an `http:`
1135
+ * document.
1136
+ *
1137
+ * Rationale: a fully https document whose playback addresses are `http://[2409:…]:6610/…`
1138
+ * is a plaintext source for the user — without this label the preview shows no warning,
1139
+ * the import succeeds, and playback later fails with `UPSTREAM_CHANGED: 没有可安全播放的
1140
+ * address` with no hint why.
1141
+ *
1142
+ * Scope and limits:
1143
+ * - only L0 documents are scanned (the whole document is already in hand at preview
1144
+ * time); L1 plugin internals cannot be pre-inspected and stay user-confirmed;
1145
+ * - at most `L0_SCAN_MAX_ITEMS` items / `L0_SCAN_MAX_URLS` urls, early return on hit;
1146
+ * - it is a **label only**: it never widens the egress policy — the peer's own
1147
+ * `insecure` flag still comes from the user's explicit `allowInsecure` confirmation
1148
+ * at import time (`egressPolicy()` stays `{ allowHttp: false }` by default).
1149
+ */
1150
+ function l0ContentInsecure(doc, docUrl) {
1151
+ const next = typeof doc.next === 'string' ? doc.next.trim() : '';
1152
+ if (next && isHttpUrl(resolveUrl(next, docUrl)))
1153
+ return true;
1154
+ const state = { urls: 0 };
1155
+ const items = Array.isArray(doc.items) ? doc.items : [];
1156
+ for (let index = 0; index < items.length && index < L0_SCAN_MAX_ITEMS; index++) {
1157
+ if (scanForPlaintextUrl(items[index], state, 0))
1158
+ return true;
1159
+ }
1160
+ return false;
1161
+ }
1162
+ /** Depth-first walk looking for any `urls` array that holds an `http://` entry. */
1163
+ function scanForPlaintextUrl(node, state, depth) {
1164
+ if (depth > L0_SCAN_MAX_DEPTH)
1165
+ return false;
1166
+ if (Array.isArray(node)) {
1167
+ for (const entry of node) {
1168
+ if (scanForPlaintextUrl(entry, state, depth + 1))
1169
+ return true;
1170
+ }
1171
+ return false;
1172
+ }
1173
+ if (!node || typeof node !== 'object')
1174
+ return false;
1175
+ for (const [key, value] of Object.entries(node)) {
1176
+ if (key === 'urls' && Array.isArray(value)) {
1177
+ for (const entry of value) {
1178
+ if (state.urls >= L0_SCAN_MAX_URLS)
1179
+ return false;
1180
+ state.urls += 1;
1181
+ // `urls` entries are either `{ url }` objects or bare strings (normalizeStreams).
1182
+ const url = typeof entry === 'string'
1183
+ ? entry
1184
+ : entry && typeof entry === 'object'
1185
+ ? entry.url
1186
+ : undefined;
1187
+ if (typeof url === 'string' && isHttpUrl(url))
1188
+ return true;
1189
+ }
1190
+ continue;
1191
+ }
1192
+ if (scanForPlaintextUrl(value, state, depth + 1))
1193
+ return true;
1194
+ }
1195
+ return false;
1196
+ }
1197
+ /** L0 search scope: the UI must be able to say "仅已加载前 N 条". */
1198
+ function localSearchScope(peers) {
1199
+ let scanned = 0;
1200
+ let truncated = false;
1201
+ let any = false;
1202
+ for (const peer of peers) {
1203
+ if (peer.localSearch !== true)
1204
+ continue;
1205
+ const candidate = peer;
1206
+ if (typeof candidate.loadedCount === 'number') {
1207
+ any = true;
1208
+ scanned += candidate.loadedCount;
1209
+ }
1210
+ if (candidate.loadTruncated === true)
1211
+ truncated = true;
1212
+ }
1213
+ if (!any)
1214
+ return {};
1215
+ return truncated ? { scanned, truncated: true } : { scanned };
1216
+ }
1217
+ /**
1218
+ * §3.1 / §3.2 解析 + §3.6 参数合并(`overrides` 优先级高于 URI query)。
1219
+ * @throws PppError INVALID_URI / BAD_PARAM(由 parsePppUri 与参数校验抛出)
1220
+ */
1221
+ function buildResolvePlan(uri, sources) {
1222
+ const parsed = parsePppUri(uri);
1223
+ // parsePppUri 已保证 `#` 只会作为 fragment 起点出现(query 内的 `#` 已判非法)。
1224
+ const hasFragment = uri.indexOf('#') >= 0;
1225
+ const params = { ...parsed.params };
1226
+ const ignoredParams = [...parsed.ignoredParams];
1227
+ for (const source of sources) {
1228
+ if (!source)
1229
+ continue;
1230
+ if (source.qn !== undefined)
1231
+ applyPppParam(params, ignoredParams, 'qn', source.qn);
1232
+ if (source.lang !== undefined)
1233
+ applyPppParam(params, ignoredParams, 'lang', source.lang);
1234
+ if (source.ep !== undefined)
1235
+ applyPppParam(params, ignoredParams, 'ep', source.ep);
1236
+ if (source.token !== undefined)
1237
+ applyPppParam(params, ignoredParams, 'token', source.token);
1238
+ if (source.h) {
1239
+ for (const [rawName, value] of Object.entries(source.h)) {
1240
+ const name = rawName.startsWith('h.') ? rawName : `h.${rawName}`;
1241
+ applyPppParam(params, ignoredParams, name, String(value));
1242
+ }
1243
+ }
1244
+ }
1245
+ if (hasFragment && params.ep !== undefined) {
1246
+ // §3.1 / §3.2:`#fragment` 与 `ep` 二选一,合并结果同现 → INVALID_URI
1247
+ throw new PppError('INVALID_URI', '地址语法非法:#fragment 与 ?ep= 同时出现(二选一)', {
1248
+ detail: '#fragment 与 ?ep= 同时出现(二选一)',
1249
+ });
1250
+ }
1251
+ let episodeId;
1252
+ if (hasFragment)
1253
+ episodeId = parsed.episodeId;
1254
+ else if (params.ep !== undefined && params.ep !== '')
1255
+ episodeId = params.ep;
1256
+ const normalized = normalizePppUri({
1257
+ peerId: parsed.peerId,
1258
+ itemId: parsed.itemId,
1259
+ episodeId,
1260
+ params,
1261
+ ignoredParams,
1262
+ // v1.0:字母随地址进入规范回显(`rate`);身份键去评级(§3.3 步骤 5 / Kevin 2026-12-05)
1263
+ rate: parsed.rate,
1264
+ });
1265
+ const plan = {
1266
+ peerId: parsed.peerId,
1267
+ itemId: parsed.itemId,
1268
+ params,
1269
+ ignoredParams,
1270
+ uri: normalized.uri,
1271
+ cacheKey: normalized.cacheKey,
1272
+ rate: parsed.rate,
1273
+ };
1274
+ if (episodeId !== undefined)
1275
+ plan.episodeId = episodeId;
1276
+ return plan;
1277
+ }
1278
+ /** §3.2 规则 3/4 + §3.3 步骤 2.2:大小写敏感匹配,回退 entryEpisodeId → 首集。 */
1279
+ function pickEpisode(plan, detail) {
1280
+ const episodes = [];
1281
+ for (const playlist of detail.playlists ?? []) {
1282
+ for (const episode of playlist.episodes ?? [])
1283
+ episodes.push(episode);
1284
+ }
1285
+ const find = (id) => episodes.find((entry) => entry.id === id);
1286
+ if (plan.episodeId !== undefined) {
1287
+ const hit = find(plan.episodeId);
1288
+ if (!hit) {
1289
+ throw new PppError('EPISODE_NOT_FOUND', `分集 ${plan.episodeId} 不存在`, {
1290
+ detail: 'episodeId 不在 playlists[].episodes[](大小写敏感)',
1291
+ });
1292
+ }
1293
+ return { id: hit.id, episode: hit };
1294
+ }
1295
+ for (const candidate of [detail.entryEpisodeId, episodes[0]?.id]) {
1296
+ if (!candidate)
1297
+ continue;
1298
+ const hit = find(candidate);
1299
+ if (hit)
1300
+ return { id: hit.id, episode: hit };
1301
+ }
1302
+ throw new PppError('EPISODE_NOT_FOUND', '该条目取不到分集', {
1303
+ detail: '§3.2 规则 4 回退(entryEpisodeId → 首集)失败',
1304
+ });
1305
+ }
1306
+ /** §5.12 分类 → §3.7 解析错误码(PPP-A-09:禁止返回未枚举码)。 */
1307
+ function toResolveCode(code, context) {
1308
+ if (code && isResolveErrorCode(code))
1309
+ return code;
1310
+ switch (code) {
1311
+ case 'NOT_FOUND':
1312
+ return context === 'episode' ? 'EPISODE_NOT_FOUND' : 'ITEM_NOT_FOUND';
1313
+ case 'INVALID_ARGUMENT':
1314
+ // 父类是 INVALID_ARGUMENT(调用方错误,不重试、不计熔断),细分回 INVALID_URI。
1315
+ return 'INVALID_URI';
1316
+ case 'AUTH_EXPIRED':
1317
+ case 'CONTENT_LOCKED':
1318
+ return 'AUTH_REQUIRED';
1319
+ default:
1320
+ // 未知 / UNSUPPORTED / NETWORK → UPSTREAM_ERROR(§5.12 未知码分类)。
1321
+ return 'UPSTREAM_ERROR';
1322
+ }
1323
+ }
1324
+ /** 插件 / 适配层错误 → §3.7 码;CANCELLED / TIMEOUT 原样上抛(§5.12 硬规则)。 */
1325
+ function mapResolveError(error, context) {
1326
+ if (isControlError(error))
1327
+ return error;
1328
+ const code = isPppError(error) ? error.code : undefined;
1329
+ const mapped = toResolveCode(code, context);
1330
+ if (isPppError(error) && error.code === mapped)
1331
+ return error;
1332
+ const message = error instanceof Error ? error.message : String(error);
1333
+ const detail = isPppError(error) ? error.detail : undefined;
1334
+ return new PppError(mapped, message, detail !== undefined ? { detail } : undefined);
1335
+ }
1336
+ /** §3.6:失败必须以 `{ ok:false, error:{code,…} }` 返回;`streams` 恒为 `[]`。 */
1337
+ function resolveFailure(error, resolvedAt, plan) {
1338
+ const code = toResolveCode(isPppError(error) ? error.code : undefined, 'other');
1339
+ const message = error instanceof Error ? error.message : String(error);
1340
+ const failure = {
1341
+ ok: false,
1342
+ error: { code, message },
1343
+ streams: [],
1344
+ ignoredParams: plan?.ignoredParams ?? [],
1345
+ resolvedAt,
1346
+ };
1347
+ const detail = isPppError(error) ? error.detail : undefined;
1348
+ if (detail !== undefined)
1349
+ failure.error.detail = detail;
1350
+ if (plan) {
1351
+ failure.uri = plan.uri;
1352
+ // 评级元数据照实交宿主(地址已解析就带上,失败也不吞)
1353
+ failure.rate = plan.rate;
1354
+ failure.mature = matureFromRate(plan.rate);
1355
+ failure.peerId = plan.peerId;
1356
+ failure.itemId = plan.itemId;
1357
+ if (plan.episodeId !== undefined)
1358
+ failure.episodeId = plan.episodeId;
1359
+ }
1360
+ return failure;
1361
+ }
1362
+ /** §3.3 步骤 1:归一化为对外 `streams[]` 形状(协议由 scheme 推导,首条为默认)。 */
1363
+ function toResolvedStream(stream, index, params) {
1364
+ const resolved = {
1365
+ url: stream.url,
1366
+ format: stream.format || inferFormat(stream.url),
1367
+ isDefault: index === 0,
1368
+ };
1369
+ const protocol = stream.url.startsWith('https:') ? 'https' : stream.url.startsWith('http:') ? 'http' : undefined;
1370
+ if (protocol)
1371
+ resolved.protocol = protocol;
1372
+ // 白名单 h.* 参数(§3.2)随地址下发;来源声明的 headers 优先(「必须附带」)。
1373
+ const headers = {};
1374
+ if (params['h.referer'])
1375
+ headers.Referer = params['h.referer'];
1376
+ if (params['h.origin'])
1377
+ headers.Origin = params['h.origin'];
1378
+ if (params['h.user-agent'])
1379
+ headers['User-Agent'] = params['h.user-agent'];
1380
+ if (stream.headers)
1381
+ Object.assign(headers, stream.headers);
1382
+ if (Object.keys(headers).length)
1383
+ resolved.headers = headers;
1384
+ if (stream.label)
1385
+ resolved.label = stream.label;
1386
+ const quality = stream.quality;
1387
+ if (typeof quality === 'string' && quality)
1388
+ resolved.quality = quality;
1389
+ return resolved;
1390
+ }
1391
+ /** §3.6 `appliedParams`:已应用参数(qn/lang/ep/h.*),**不含 token 明文**。 */
1392
+ function appliedParamsOf(params) {
1393
+ const applied = {};
1394
+ if (params.qn !== undefined)
1395
+ applied.qn = params.qn;
1396
+ if (params.lang !== undefined)
1397
+ applied.lang = params.lang;
1398
+ if (params.ep !== undefined)
1399
+ applied.ep = params.ep;
1400
+ const headers = {};
1401
+ for (const [name, value] of Object.entries(params)) {
1402
+ if (name.startsWith('h.'))
1403
+ headers[name.slice(2)] = value;
1404
+ }
1405
+ if (Object.keys(headers).length)
1406
+ applied.h = headers;
1407
+ return applied;
1408
+ }
1409
+ export { parseManifest, parseStaticDoc, isStaticDoc, resolveUrl, CROSS_PEER_CAPABILITIES };
1410
+ //# sourceMappingURL=runtime.js.map