krillplayer-plugin 0.2.0 → 0.4.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.
- package/README.md +18 -0
- package/dist/cli.js +277 -46
- package/dist/crypto.d.ts +8 -0
- package/dist/crypto.js +1609 -0
- package/dist/zip.d.ts +13 -0
- package/dist/zip.js +68 -0
- package/package.json +10 -2
- package/skill/krillplayer-plugin/SKILL.md +2 -1
- package/skill/krillplayer-plugin/references/cases.md +21 -0
- package/skill/krillplayer-plugin/references/contract.d.ts +81 -41
package/README.md
CHANGED
|
@@ -28,6 +28,23 @@ npx krillplayer-plugin check
|
|
|
28
28
|
|
|
29
29
|
插件里只 import 类型:`import type { BrowseSlot, PlaySlot, PluginManifest } from "krillplayer-plugin";`。类型、`krillplayer` 对象与每个槽位的调用约定都在 `contract.d.ts`,它由 App 仓库的契约生成器产出,开头写着契约的修订号。App 只运行修订号与它一致的插件;契约升修订时本包随之发新版本,Skill 里的参考跟着重新生成。
|
|
30
30
|
|
|
31
|
+
## 单元测试与发布脚本用的入口
|
|
32
|
+
|
|
33
|
+
用例一次只跑一个调用。用例测不到的(带随机数的加密、自己的发布脚本)可以写 Node 的单元测试,用本包的两个入口,它们只在 Node 里用,类型要带 Node 的(`@types/node`):
|
|
34
|
+
|
|
35
|
+
| 入口 | 导出 | 用途 |
|
|
36
|
+
|---|---|---|
|
|
37
|
+
| `krillplayer-plugin/zip` | `writeZip(entries)`、`readZip(zip)` | 读写插件包,与 `bundle` 同一份代码:同样的文件、同样的顺序写出同样的字节。签名时读出包里的文件 |
|
|
38
|
+
| `krillplayer-plugin/crypto` | `createCrypto()` | 新建一份 `krillplayer.crypto`,与 `trial` 里插件拿到的是同一份实现,单元测试里当假的 `krillplayer` 的 `crypto` |
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
import { createCrypto } from "krillplayer-plugin/crypto";
|
|
42
|
+
import { readZip } from "krillplayer-plugin/zip";
|
|
43
|
+
|
|
44
|
+
const krillplayer = { crypto: createCrypto(), /* 测试要用的别的成员 */ };
|
|
45
|
+
const manifest = readZip(zip).get("manifest.json");
|
|
46
|
+
```
|
|
47
|
+
|
|
31
48
|
## 给 AI
|
|
32
49
|
|
|
33
50
|
```sh
|
|
@@ -87,5 +104,6 @@ npx krillplayer-plugin skill
|
|
|
87
104
|
|
|
88
105
|
## 更新记录
|
|
89
106
|
|
|
107
|
+
- **0.4.0**:`danmaku.send` 可以返回发送会话(WebSocket),App 替插件连、发、等,收到的帧交给新的 `danmaku.sendDecode` 判;导出它的插件能力是 `danmakuSendSession`。用例多了假服务器 `socket`。契约修订号不变。完整记录见 `CHANGELOG.md`。
|
|
90
108
|
- **0.1.2**:契约去掉资料库槽位 `library`(`list`、`read`、`changes`、`ids`)与能力 `library`、`libraryChanges`,App 不再整库扫描来源。还导出 `library` 的插件打包失败,删掉这个导出即可;已经装着的旧版本照常运行,App 不调它。契约修订号不变。
|
|
91
109
|
- **0.1.1**:契约加上在直播间发弹幕的 `danmaku.send`(能力 `danmakuSend`)。
|
package/dist/cli.js
CHANGED
|
@@ -77,9 +77,11 @@ var Capability = enumeration("Capability", [
|
|
|
77
77
|
"status",
|
|
78
78
|
"login",
|
|
79
79
|
"playbackReport",
|
|
80
|
-
"views",
|
|
81
80
|
"danmakuSend",
|
|
82
|
-
"browseLists"
|
|
81
|
+
"browseLists",
|
|
82
|
+
"playerPanels",
|
|
83
|
+
"cardActions",
|
|
84
|
+
"danmakuSendSession"
|
|
83
85
|
]);
|
|
84
86
|
var Media = enumeration("Media", ["video", "audio"]);
|
|
85
87
|
var ChannelKind = enumeration("ChannelKind", ["creator", "station", "podcast"]);
|
|
@@ -418,32 +420,31 @@ var Playable = object("Playable", {
|
|
|
418
420
|
// 这一路的原始文件名,给字幕插件与弹幕插件匹配用(contract.md 3.1);不给时内核用条目的文件名或标题。
|
|
419
421
|
filename: optional(string)
|
|
420
422
|
});
|
|
421
|
-
var
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
image: optional(string),
|
|
427
|
-
text: optional(string),
|
|
423
|
+
var Comment = object("Comment", {
|
|
424
|
+
id: string,
|
|
425
|
+
author: string,
|
|
426
|
+
text: string,
|
|
427
|
+
avatar: optional(string),
|
|
428
428
|
time: optional(number),
|
|
429
|
-
|
|
429
|
+
likes: optional(integer)
|
|
430
430
|
});
|
|
431
|
-
var
|
|
432
|
-
|
|
431
|
+
var EntriesPanel = object("EntriesPanel", {
|
|
432
|
+
kind: constant("entries"),
|
|
433
433
|
title: optional(string),
|
|
434
|
-
|
|
434
|
+
entries: array(Entry),
|
|
435
|
+
next: optional(string),
|
|
436
|
+
maxAge: optional(number)
|
|
435
437
|
});
|
|
436
|
-
var
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
sections: array(Section),
|
|
438
|
+
var CommentsPanel = object("CommentsPanel", {
|
|
439
|
+
kind: constant("comments"),
|
|
440
|
+
comments: array(Comment),
|
|
440
441
|
next: optional(string),
|
|
441
|
-
maxAge: optional(number)
|
|
442
|
-
empty: optional(string)
|
|
443
|
-
}, "PageContent");
|
|
444
|
-
var ActionResult = object("ActionResult", {
|
|
445
|
-
message: optional(string)
|
|
442
|
+
maxAge: optional(number)
|
|
446
443
|
});
|
|
444
|
+
var PanelPage = union("PanelPage", "kind", [EntriesPanel, CommentsPanel], "PanelContent");
|
|
445
|
+
var ActionMessage = object("ActionMessage", { kind: constant("message"), message: string });
|
|
446
|
+
var ActionEntries = object("ActionEntries", { kind: constant("entries"), title: optional(string), entries: array(Entry) });
|
|
447
|
+
var ActionResult = union("ActionResult", "kind", [ActionMessage, ActionEntries]);
|
|
447
448
|
var ChannelStatus = object("ChannelStatus", {
|
|
448
449
|
id: string,
|
|
449
450
|
live: enumeration("ChannelLive", ["online", "offline", "unknown"], "unknown"),
|
|
@@ -484,6 +485,24 @@ var LiveDanmakuConnection = object("LiveDanmakuConnection", {
|
|
|
484
485
|
heartbeat: optional(object("DanmakuHeartbeat", { frame: DanmakuFrame, interval: number })),
|
|
485
486
|
recent: optional(array(DanmakuComment))
|
|
486
487
|
});
|
|
488
|
+
var DANMAKU_SEND_LIMITS = { waitSeconds: 10, sessionSeconds: 20 };
|
|
489
|
+
var DanmakuSendWait = object("DanmakuSendWait", {
|
|
490
|
+
seconds: number,
|
|
491
|
+
outcome: enumeration("DanmakuSendOutcome", ["sent", "failed"], "failed")
|
|
492
|
+
});
|
|
493
|
+
var DanmakuSendSession = object("DanmakuSendSession", {
|
|
494
|
+
url: string,
|
|
495
|
+
headers: optional(map(string)),
|
|
496
|
+
handshake: array(DanmakuFrame),
|
|
497
|
+
wait: DanmakuSendWait,
|
|
498
|
+
state: optional(string)
|
|
499
|
+
});
|
|
500
|
+
var DanmakuSendStep = object("DanmakuSendStep", {
|
|
501
|
+
replies: optional(array(DanmakuFrame)),
|
|
502
|
+
sent: optional(boolean),
|
|
503
|
+
wait: optional(DanmakuSendWait),
|
|
504
|
+
state: optional(string)
|
|
505
|
+
});
|
|
487
506
|
var DanmakuBatch = object("DanmakuBatch", {
|
|
488
507
|
messages: array(DanmakuComment),
|
|
489
508
|
replies: optional(array(DanmakuFrame)),
|
|
@@ -779,11 +798,15 @@ var SLOT_RULES = {
|
|
|
779
798
|
capabilities: { subtitles: ["list"], subtitleSearch: ["search"] }
|
|
780
799
|
},
|
|
781
800
|
// send 是在直播间里发一条弹幕(contract.md 2.7),单独一项能力:只认 danmaku 的旧内核不认识 danmakuSend,跳过,不会去调它。
|
|
801
|
+
// 导出 sendDecode 的插件的 send 可以返回发送会话,能力是 danmakuSendSession 而不是 danmakuSend:只认 danmakuSend 的旧内核
|
|
802
|
+
// 不会去调它、把会话当成发出去了。
|
|
782
803
|
danmaku: {
|
|
783
|
-
functions: ["connect", "decode", "segment", "match", "comments", "send"],
|
|
804
|
+
functions: ["connect", "decode", "segment", "match", "comments", "send", "sendDecode"],
|
|
784
805
|
required: [],
|
|
785
806
|
pairs: [["connect", "decode"], ["match", "comments"]],
|
|
786
|
-
|
|
807
|
+
needs: { sendDecode: "send" },
|
|
808
|
+
capabilities: { danmaku: ["connect", "segment"], danmakuMatch: ["match"], danmakuSend: ["send"], danmakuSendSession: ["sendDecode"] },
|
|
809
|
+
supersedes: { danmakuSendSession: "danmakuSend" }
|
|
787
810
|
},
|
|
788
811
|
status: { functions: ["check", "images"], required: ["check"], pairs: [], capabilities: { status: ["check"] } },
|
|
789
812
|
login: {
|
|
@@ -793,8 +816,9 @@ var SLOT_RULES = {
|
|
|
793
816
|
capabilities: { login: ["methods"] }
|
|
794
817
|
},
|
|
795
818
|
playbackReport: { functions: ["report"], required: ["report"], pairs: [], capabilities: { playbackReport: ["report"] } },
|
|
796
|
-
// 组件页面 page 去掉了(ADR 0040
|
|
797
|
-
|
|
819
|
+
// 组件页面 page 去掉了(ADR 0040),剩下播放器面板与卡片操作,都交数据(#753)。面板与操作各一项能力,
|
|
820
|
+
// 不再是 views:交组件格式的旧插件打的是 views,新内核不认识、跳过,不会按数据去解它;旧内核也不认识这两项,不会按组件格式去解新插件。
|
|
821
|
+
views: { functions: ["panel", "action"], required: [], pairs: [], capabilities: { playerPanels: ["panel"], cardActions: ["action"] } },
|
|
798
822
|
// 顶层的 parameters 不算能力(contract.md 第 2 节)。
|
|
799
823
|
parameters: { functions: ["options"], required: ["options"], pairs: [], capabilities: {} }
|
|
800
824
|
};
|
|
@@ -828,7 +852,9 @@ var SLOT_RETURNS = {
|
|
|
828
852
|
decode: { schema: DanmakuBatch },
|
|
829
853
|
segment: { schema: DanmakuSegment },
|
|
830
854
|
match: { schema: array(DanmakuMatch) },
|
|
831
|
-
comments: { schema: DanmakuSegment }
|
|
855
|
+
comments: { schema: DanmakuSegment },
|
|
856
|
+
send: { schema: DanmakuSendSession, nullable: true },
|
|
857
|
+
sendDecode: { schema: DanmakuSendStep }
|
|
832
858
|
},
|
|
833
859
|
status: { check: { schema: array(ChannelStatus) }, images: { schema: array(ChannelImage) } },
|
|
834
860
|
login: {
|
|
@@ -837,7 +863,7 @@ var SLOT_RETURNS = {
|
|
|
837
863
|
poll: { schema: LoginPoll },
|
|
838
864
|
account: { schema: LoginAccount, nullable: true }
|
|
839
865
|
},
|
|
840
|
-
views: { panel: { schema:
|
|
866
|
+
views: { panel: { schema: PanelPage }, action: { schema: ActionResult } },
|
|
841
867
|
parameters: { options: { schema: array(Option) } },
|
|
842
868
|
resolve: { "": { schema: Resolved, nullable: true } }
|
|
843
869
|
};
|
|
@@ -877,6 +903,7 @@ var NOT_YET_USED = [
|
|
|
877
903
|
"ChannelRef.kind",
|
|
878
904
|
"ChannelStatus.latest",
|
|
879
905
|
"CollectionRef.kind",
|
|
906
|
+
"Comment.avatar",
|
|
880
907
|
"CommentGift.count",
|
|
881
908
|
"CommentGift.name",
|
|
882
909
|
"CommentImage.height",
|
|
@@ -915,7 +942,6 @@ var NOT_YET_USED = [
|
|
|
915
942
|
"MusicPlaylist.count",
|
|
916
943
|
"MusicPlaylist.owner",
|
|
917
944
|
"MusicPlaylist.summary",
|
|
918
|
-
"MusicSection.kind",
|
|
919
945
|
"OnDemand.index",
|
|
920
946
|
"OnDemand.summary",
|
|
921
947
|
"OnDemand.version",
|
|
@@ -1380,7 +1406,7 @@ var Chain = class {
|
|
|
1380
1406
|
let headers2 = becomesGet ? without(previous.headers, BODY_HEADERS) : previous.headers;
|
|
1381
1407
|
if (this.seen.has(`${method} ${address.href}`)) throw this.refuse("redirect-loop", address, `redirect loop at ${this.label(address)}`);
|
|
1382
1408
|
const downgrade = previous.address.scheme === "https" && address.scheme === "http";
|
|
1383
|
-
if (downgrade && this.use !== "playback-follow" && this.use !== "playback-probe") {
|
|
1409
|
+
if (downgrade && this.use !== "playback" && this.use !== "playback-follow" && this.use !== "playback-probe") {
|
|
1384
1410
|
throw this.refuse("no-downgrade", address, `will not follow a redirect from https to http at ${this.label(address)}`);
|
|
1385
1411
|
}
|
|
1386
1412
|
const hostClass = this.classify(address.host);
|
|
@@ -2895,6 +2921,19 @@ function createSubtle() {
|
|
|
2895
2921
|
unwrapKey
|
|
2896
2922
|
};
|
|
2897
2923
|
}
|
|
2924
|
+
var DIGESTS = /* @__PURE__ */ new Map([["sha-1", "SHA-1"], ["sha-256", "SHA-256"], ["sha-384", "SHA-384"], ["sha-512", "SHA-512"]]);
|
|
2925
|
+
async function plainDigest(algorithm, data) {
|
|
2926
|
+
const name2 = DIGESTS.get(algorithm.toLowerCase());
|
|
2927
|
+
if (name2 === void 0) throw new TypeError(`unsupported digest ${algorithm}`);
|
|
2928
|
+
return new Uint8Array(await subtle().digest(name2, typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data)));
|
|
2929
|
+
}
|
|
2930
|
+
function createCrypto() {
|
|
2931
|
+
return {
|
|
2932
|
+
randomBytes: (length) => globalThis.crypto.getRandomValues(new Uint8Array(length)),
|
|
2933
|
+
digest: plainDigest,
|
|
2934
|
+
subtle: createSubtle()
|
|
2935
|
+
};
|
|
2936
|
+
}
|
|
2898
2937
|
|
|
2899
2938
|
// host/krillplayer.ts
|
|
2900
2939
|
function userAddressesOf(manifest, parameters) {
|
|
@@ -2912,7 +2951,6 @@ function userHostsOf(manifest, parameters) {
|
|
|
2912
2951
|
});
|
|
2913
2952
|
}
|
|
2914
2953
|
var STATUS_SLOT_CAPABILITIES = /* @__PURE__ */ new Set(["http", "decompress", "crypto", "formats", "log", "cache", "credentials", "parameters", "error"]);
|
|
2915
|
-
var DIGESTS = /* @__PURE__ */ new Map([["sha-1", "SHA-1"], ["sha-256", "SHA-256"], ["sha-384", "SHA-384"], ["sha-512", "SHA-512"]]);
|
|
2916
2954
|
var COMPRESSION_FORMATS = /* @__PURE__ */ new Set(["gzip", "deflate", "deflate-raw"]);
|
|
2917
2955
|
function createCache(now2 = Date.now) {
|
|
2918
2956
|
const entries = /* @__PURE__ */ new Map();
|
|
@@ -3016,8 +3054,8 @@ function createDerivedURLs() {
|
|
|
3016
3054
|
},
|
|
3017
3055
|
async parsed(data, guideURLs) {
|
|
3018
3056
|
if (typeof data === "string" || guideURLs.length === 0) return;
|
|
3019
|
-
const
|
|
3020
|
-
if (!state().bodies.includes(
|
|
3057
|
+
const digest2 = hex(await crypto.subtle.digest("SHA-256", toBytes(data)));
|
|
3058
|
+
if (!state().bodies.includes(digest2)) return;
|
|
3021
3059
|
for (const url of guideURLs) keep(state().urls, url, DERIVED_URLS_KEPT);
|
|
3022
3060
|
},
|
|
3023
3061
|
// 从用户填的地址跳到的派生主机(derived-lifetime):这个实例之后可以直接请求,只读、不带凭证。最多留 REMEMBERED_HOSTS 台。
|
|
@@ -3167,11 +3205,7 @@ function createKrillPlayer({
|
|
|
3167
3205
|
}
|
|
3168
3206
|
},
|
|
3169
3207
|
decompress: (format2, data) => decompress(format2, data),
|
|
3170
|
-
crypto:
|
|
3171
|
-
randomBytes: (length) => crypto.getRandomValues(new Uint8Array(length)),
|
|
3172
|
-
digest: digest2,
|
|
3173
|
-
subtle: createSubtle()
|
|
3174
|
-
},
|
|
3208
|
+
crypto: createCrypto(),
|
|
3175
3209
|
formats: {
|
|
3176
3210
|
async m3u(data) {
|
|
3177
3211
|
const playlist = parseM3U(data);
|
|
@@ -3327,10 +3361,90 @@ async function decompress(format2, data, limit = FORMAT_LIMITS.decompressedBytes
|
|
|
3327
3361
|
}
|
|
3328
3362
|
return output;
|
|
3329
3363
|
}
|
|
3330
|
-
|
|
3331
|
-
|
|
3332
|
-
|
|
3333
|
-
|
|
3364
|
+
|
|
3365
|
+
// host/danmaku-send.ts
|
|
3366
|
+
var DanmakuSendFailure = class extends Error {
|
|
3367
|
+
};
|
|
3368
|
+
async function runSendSession({
|
|
3369
|
+
session,
|
|
3370
|
+
grants,
|
|
3371
|
+
open,
|
|
3372
|
+
decode: decode2,
|
|
3373
|
+
lookup: lookup2
|
|
3374
|
+
}) {
|
|
3375
|
+
const secrets = (grants.secrets ?? []).filter((secret) => secret !== "");
|
|
3376
|
+
const texts = (frames) => frames.map(frameText);
|
|
3377
|
+
const headers2 = session.headers ?? {};
|
|
3378
|
+
let pass;
|
|
3379
|
+
try {
|
|
3380
|
+
const chain = new Chain("danmaku", grants);
|
|
3381
|
+
pass = chain.first({ url: session.url, headers: headers2, frames: texts(session.handshake) });
|
|
3382
|
+
const looked = pass.publicOnly === null ? void 0 : lookup2?.(pass.address.host);
|
|
3383
|
+
if (looked !== void 0) chain.resolved(looked.addresses);
|
|
3384
|
+
} catch (error) {
|
|
3385
|
+
throw new DanmakuSendFailure(`danmaku send: ${error.message}`);
|
|
3386
|
+
}
|
|
3387
|
+
const inFrame = (frame2, secret) => frame2.data === void 0 ? (frame2.text ?? "").includes(secret) : Buffer.from(frame2.data).includes(Buffer.from(secret, "utf8"));
|
|
3388
|
+
const carrying = (strings, frames) => secrets.some((secret) => strings.some((text) => text.includes(secret)) || frames.some((frame2) => inFrame(frame2, secret)));
|
|
3389
|
+
const mayCarry = carrying([session.url, ...Object.keys(headers2), ...Object.values(headers2)], session.handshake);
|
|
3390
|
+
const socket = open(pass.address.href, pass.headers);
|
|
3391
|
+
let expired = null;
|
|
3392
|
+
let shookHands = false;
|
|
3393
|
+
let timer;
|
|
3394
|
+
const end = (outcome) => {
|
|
3395
|
+
expired ??= outcome;
|
|
3396
|
+
socket.close();
|
|
3397
|
+
};
|
|
3398
|
+
const arm = (wait) => {
|
|
3399
|
+
clearTimeout(timer);
|
|
3400
|
+
const seconds = Math.min(Math.max(wait.seconds, 0), DANMAKU_SEND_LIMITS.waitSeconds);
|
|
3401
|
+
timer = setTimeout(() => end(shookHands ? wait.outcome : "failed"), seconds * 1e3);
|
|
3402
|
+
};
|
|
3403
|
+
const cap = setTimeout(() => end("failed"), DANMAKU_SEND_LIMITS.sessionSeconds * 1e3);
|
|
3404
|
+
const closed = () => {
|
|
3405
|
+
if (expired === "sent") return;
|
|
3406
|
+
throw new DanmakuSendFailure(expired === null ? "danmaku send: the connection closed before the plugin decided" : "danmaku send: no decision before the deadline");
|
|
3407
|
+
};
|
|
3408
|
+
try {
|
|
3409
|
+
arm(session.wait);
|
|
3410
|
+
try {
|
|
3411
|
+
for (const frame2 of session.handshake) await socket.send(frame2);
|
|
3412
|
+
} catch {
|
|
3413
|
+
return closed();
|
|
3414
|
+
}
|
|
3415
|
+
shookHands = true;
|
|
3416
|
+
arm(session.wait);
|
|
3417
|
+
let state = session.state ?? null;
|
|
3418
|
+
for (; ; ) {
|
|
3419
|
+
let frame2;
|
|
3420
|
+
try {
|
|
3421
|
+
frame2 = await socket.receive();
|
|
3422
|
+
} catch {
|
|
3423
|
+
return closed();
|
|
3424
|
+
}
|
|
3425
|
+
const step = await decode2(frame2, state);
|
|
3426
|
+
if (step.state !== void 0) state = step.state;
|
|
3427
|
+
for (const reply of step.replies ?? []) {
|
|
3428
|
+
if (!mayCarry && carrying([], [reply])) {
|
|
3429
|
+
throw new DanmakuSendFailure("danmaku send: a reply carries credentials the handshake did not");
|
|
3430
|
+
}
|
|
3431
|
+
try {
|
|
3432
|
+
await socket.send(reply);
|
|
3433
|
+
} catch {
|
|
3434
|
+
return closed();
|
|
3435
|
+
}
|
|
3436
|
+
}
|
|
3437
|
+
if (step.sent === true) return;
|
|
3438
|
+
if (step.wait !== void 0) arm(step.wait);
|
|
3439
|
+
}
|
|
3440
|
+
} finally {
|
|
3441
|
+
clearTimeout(timer);
|
|
3442
|
+
clearTimeout(cap);
|
|
3443
|
+
socket.close();
|
|
3444
|
+
}
|
|
3445
|
+
}
|
|
3446
|
+
function frameText(frame2) {
|
|
3447
|
+
return frame2.data === void 0 ? frame2.text ?? "" : Buffer.from(frame2.data).toString("latin1");
|
|
3334
3448
|
}
|
|
3335
3449
|
|
|
3336
3450
|
// contract/validate.ts
|
|
@@ -4043,6 +4157,76 @@ async function readCases(directory) {
|
|
|
4043
4157
|
return { name: relative(directory, file), data: JSON.parse(raw), byteOrderMark: holdsByteOrderMark(raw) };
|
|
4044
4158
|
}));
|
|
4045
4159
|
}
|
|
4160
|
+
var frameJSON = (frame2) => frame2.data === void 0 ? { text: frame2.text ?? "" } : { data: bytesToJSON(frame2.data) };
|
|
4161
|
+
var frameOf = (json) => "data" in json ? { data: new Uint8Array(Buffer.from(json.data.$bytes, "base64")) } : { text: json.text };
|
|
4162
|
+
function scriptedSockets(script) {
|
|
4163
|
+
const problems = [];
|
|
4164
|
+
let opened = false;
|
|
4165
|
+
let step = 0;
|
|
4166
|
+
const open = (url, headers2) => {
|
|
4167
|
+
if (opened) problems.push(`a second socket to ${url}`);
|
|
4168
|
+
opened = true;
|
|
4169
|
+
if (script === void 0) problems.push(`unscripted socket to ${url}`);
|
|
4170
|
+
else if (url !== script.url) problems.push(`socket to ${url}, scripted ${script.url}`);
|
|
4171
|
+
else if (script.headers !== void 0 && canonicalHeaders(script.headers) !== canonicalHeaders(headers2)) {
|
|
4172
|
+
problems.push(`socket headers ${canonicalHeaders(headers2)}, scripted ${canonicalHeaders(script.headers)}`);
|
|
4173
|
+
}
|
|
4174
|
+
const steps = problems.length === 0 && script !== void 0 ? script.script : [];
|
|
4175
|
+
const inbox = [];
|
|
4176
|
+
const waiting = [];
|
|
4177
|
+
let closed = problems.length > 0;
|
|
4178
|
+
const shut = () => {
|
|
4179
|
+
closed = true;
|
|
4180
|
+
for (const waiter of waiting.splice(0)) waiter.reject(new Error("socket closed"));
|
|
4181
|
+
};
|
|
4182
|
+
const advance = () => {
|
|
4183
|
+
while (!closed && step < steps.length) {
|
|
4184
|
+
const current = steps[step];
|
|
4185
|
+
if ("client" in current) return;
|
|
4186
|
+
step += 1;
|
|
4187
|
+
if ("close" in current) return shut();
|
|
4188
|
+
const frame2 = frameOf(current.server);
|
|
4189
|
+
const waiter = waiting.shift();
|
|
4190
|
+
if (waiter === void 0) inbox.push(frame2);
|
|
4191
|
+
else waiter.resolve(frame2);
|
|
4192
|
+
}
|
|
4193
|
+
};
|
|
4194
|
+
advance();
|
|
4195
|
+
return {
|
|
4196
|
+
async send(frame2) {
|
|
4197
|
+
if (closed) throw new Error("socket closed");
|
|
4198
|
+
const current = steps[step];
|
|
4199
|
+
if (current === void 0 || !("client" in current)) {
|
|
4200
|
+
problems.push(`unscripted frame ${canonical(frameJSON(frame2))}`);
|
|
4201
|
+
return shut();
|
|
4202
|
+
}
|
|
4203
|
+
if (canonical(frameJSON(frame2)) !== canonical(current.client)) {
|
|
4204
|
+
problems.push(`frame differs at socket step ${step + 1}
|
|
4205
|
+
expected ${canonical(current.client)}
|
|
4206
|
+
actual ${canonical(frameJSON(frame2))}`);
|
|
4207
|
+
return shut();
|
|
4208
|
+
}
|
|
4209
|
+
step += 1;
|
|
4210
|
+
advance();
|
|
4211
|
+
},
|
|
4212
|
+
receive() {
|
|
4213
|
+
const frame2 = inbox.shift();
|
|
4214
|
+
if (frame2 !== void 0) return Promise.resolve(frame2);
|
|
4215
|
+
if (closed) return Promise.reject(new Error("socket closed"));
|
|
4216
|
+
return new Promise((resolve4, reject) => waiting.push({ resolve: resolve4, reject }));
|
|
4217
|
+
},
|
|
4218
|
+
close: shut
|
|
4219
|
+
};
|
|
4220
|
+
};
|
|
4221
|
+
return {
|
|
4222
|
+
open,
|
|
4223
|
+
problems: () => [
|
|
4224
|
+
...problems,
|
|
4225
|
+
...script !== void 0 && !opened ? [`scripted socket to ${script.url} was not opened`] : [],
|
|
4226
|
+
...opened && script !== void 0 && problems.length === 0 && step < script.script.length ? [`socket script stopped at step ${step + 1} of ${script.script.length}`] : []
|
|
4227
|
+
]
|
|
4228
|
+
};
|
|
4229
|
+
}
|
|
4046
4230
|
|
|
4047
4231
|
// trial-runner/engine.ts
|
|
4048
4232
|
import { execFile, spawn } from "node:child_process";
|
|
@@ -4780,6 +4964,9 @@ function capabilitiesOf(namespace) {
|
|
|
4780
4964
|
problems.push(`${name2}.${present} needs ${name2}.${missing}`);
|
|
4781
4965
|
}
|
|
4782
4966
|
}
|
|
4967
|
+
for (const [member, needed] of Object.entries(rule.needs ?? {})) {
|
|
4968
|
+
if (has(member) && !has(needed)) problems.push(`${name2}.${member} needs ${name2}.${needed}`);
|
|
4969
|
+
}
|
|
4783
4970
|
const matched = Object.entries(rule.capabilities).filter(([, any]) => any.some(has)).map(([capability]) => capability);
|
|
4784
4971
|
const superseded = new Set(matched.flatMap((capability) => rule.supersedes?.[capability] ?? []));
|
|
4785
4972
|
const generated = matched.filter((capability) => !superseded.has(capability));
|
|
@@ -4940,6 +5127,7 @@ async function readPlugin(path) {
|
|
|
4940
5127
|
language: manifest.language,
|
|
4941
5128
|
dictionaries: dictionariesIn(files2),
|
|
4942
5129
|
exports: checked.exports,
|
|
5130
|
+
capabilities: capabilities ?? [],
|
|
4943
5131
|
// 清单用了内核留用的参数名(contract.md 6.1)和静态检查拦下的一样判红。
|
|
4944
5132
|
violations: [...checked.violations, ...checkManifest({ ...manifest, capabilities }).map((problem) => ` manifest.json: ${problem}`)]
|
|
4945
5133
|
};
|
|
@@ -5004,15 +5192,38 @@ async function runSlotCase(plugin2, testCase) {
|
|
|
5004
5192
|
let outcome;
|
|
5005
5193
|
let written;
|
|
5006
5194
|
const problems = [];
|
|
5195
|
+
const sockets = scriptedSockets(testCase.socket);
|
|
5007
5196
|
const context = await openSlot(plugin2, testCase, replay.fetch, testCase.credentials ?? null, (write) => {
|
|
5008
5197
|
written = write;
|
|
5009
5198
|
}, metadata, files2);
|
|
5010
5199
|
try {
|
|
5011
5200
|
const value = await context.call(testCase.slot, testCase.call ?? "", testCase.args.map(fromJSON));
|
|
5012
|
-
|
|
5013
|
-
|
|
5201
|
+
const contract = contractProblems(testCase, value);
|
|
5202
|
+
problems.push(...contract);
|
|
5203
|
+
if (isSendSession(testCase, value) && contract.length === 0) {
|
|
5204
|
+
if (!plugin2.capabilities.includes("danmakuSendSession")) {
|
|
5205
|
+
throw new DanmakuSendFailure("danmaku send: the plugin returned a send session but does not export danmaku.sendDecode");
|
|
5206
|
+
}
|
|
5207
|
+
await runSendSession({
|
|
5208
|
+
session: value,
|
|
5209
|
+
grants: sendGrants(plugin2, testCase),
|
|
5210
|
+
open: sockets.open,
|
|
5211
|
+
decode: async (frame2, state) => {
|
|
5212
|
+
const step = await context.call("danmaku", "sendDecode", [frame2, state]);
|
|
5213
|
+
const stepProblems = contractProblems({ slot: "danmaku", call: "sendDecode" }, step);
|
|
5214
|
+
if (stepProblems.length > 0) {
|
|
5215
|
+
problems.push(...stepProblems);
|
|
5216
|
+
throw new DanmakuSendFailure("danmaku send: sendDecode returned a step outside the contract");
|
|
5217
|
+
}
|
|
5218
|
+
return step;
|
|
5219
|
+
}
|
|
5220
|
+
});
|
|
5221
|
+
outcome = { output: null };
|
|
5222
|
+
} else {
|
|
5223
|
+
outcome = { output: toJSON(value) };
|
|
5224
|
+
}
|
|
5014
5225
|
} catch (error) {
|
|
5015
|
-
if (!isCallFailure(error)) throw error;
|
|
5226
|
+
if (!isCallFailure(error) && !(error instanceof DanmakuSendFailure)) throw error;
|
|
5016
5227
|
outcome = { error: structuredError(error), message: describeError(error) };
|
|
5017
5228
|
} finally {
|
|
5018
5229
|
context.close();
|
|
@@ -5021,7 +5232,8 @@ async function runSlotCase(plugin2, testCase) {
|
|
|
5021
5232
|
...replay.unrecorded.map((request) => `unrecorded request ${request}`),
|
|
5022
5233
|
...replay.pending.map(({ request }) => `recorded request not sent ${request.method} ${request.url}`),
|
|
5023
5234
|
...metadata.problems(),
|
|
5024
|
-
...files2.problems()
|
|
5235
|
+
...files2.problems(),
|
|
5236
|
+
...sockets.problems()
|
|
5025
5237
|
);
|
|
5026
5238
|
if ("output" in outcome) {
|
|
5027
5239
|
if (testCase.error !== void 0) problems.push(`should throw ${canonical(testCase.error)}, returned ${canonical(outcome.output)}`);
|
|
@@ -5044,6 +5256,22 @@ async function runSlotCase(plugin2, testCase) {
|
|
|
5044
5256
|
}
|
|
5045
5257
|
return problems.length === 0 ? { status: "passed" } : { status: "failed", reason: problems.join("\n ") };
|
|
5046
5258
|
}
|
|
5259
|
+
function isSendSession(testCase, value) {
|
|
5260
|
+
return testCase.slot === "danmaku" && testCase.call === "send" && value !== null && value !== void 0;
|
|
5261
|
+
}
|
|
5262
|
+
function sendGrants(plugin2, testCase) {
|
|
5263
|
+
const parameters = testCase.parameters ?? null;
|
|
5264
|
+
const user = plugin2.network.userProvidedURLs === true && parameters !== null;
|
|
5265
|
+
return {
|
|
5266
|
+
declared: plugin2.network.hosts,
|
|
5267
|
+
user: user ? userHostsOf(plugin2, parameters) : [],
|
|
5268
|
+
userAddresses: user ? userAddressesOf(plugin2, parameters) : [],
|
|
5269
|
+
secrets: [
|
|
5270
|
+
...credentialValues(testCase.credentials ?? null),
|
|
5271
|
+
...plugin2.parameters.filter((parameter) => parameter.secret).flatMap((parameter) => parameters !== null && Object.hasOwn(parameters, parameter.name) && parameters[parameter.name] !== "" ? [parameters[parameter.name]] : [])
|
|
5272
|
+
]
|
|
5273
|
+
};
|
|
5274
|
+
}
|
|
5047
5275
|
function report(results, log) {
|
|
5048
5276
|
const counts = { passed: 0, skipped: 0, failed: 0 };
|
|
5049
5277
|
for (const { name: name2, outcome } of results) {
|
|
@@ -5082,6 +5310,9 @@ async function recordCommand(pluginDirectory, { slot, call: callName, args, cred
|
|
|
5082
5310
|
const problems = contractProblems({ slot, call: callName }, value);
|
|
5083
5311
|
if (problems.length > 0) throw new RecordRefused(`the plugin's output does not match the contract, nothing was recorded:
|
|
5084
5312
|
${problems.join("\n ")}`);
|
|
5313
|
+
if (isSendSession({ slot, call: callName }, value)) {
|
|
5314
|
+
throw new RecordRefused("danmaku.send returned a send session; record does not open sockets, write the case's socket script by hand (see the skill's references/cases.md, section socket)");
|
|
5315
|
+
}
|
|
5085
5316
|
return { output: toJSON(value) };
|
|
5086
5317
|
};
|
|
5087
5318
|
await settle(invokeSlot(plugin2, { slot, call: callName, args, parameters, appKeys, output: null }, recording.fetch, credentials));
|
package/dist/crypto.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// krillplayer-plugin/crypto:试跑器交给插件的 krillplayer.crypto,给插件的单元测试当假的 krillplayer 用,只在 Node 里用。
|
|
2
|
+
import type { KrillPlayer } from "../skill/krillplayer-plugin/references/contract.js";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* 新建一份 krillplayer.crypto(randomBytes、digest、subtle),与 `krillplayer-plugin trial` 里插件拿到的是同一份实现:
|
|
6
|
+
* 收的参数、PEM 公私钥、报错文本都一样。
|
|
7
|
+
*/
|
|
8
|
+
export function createCrypto(): KrillPlayer["crypto"];
|