krillplayer-plugin 0.1.0 → 0.1.1
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/dist/cli.js +796 -498
- package/package.json +2 -2
- package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-connect.json +23 -0
- package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-decode.json +19 -0
- package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-content-rejected.json +31 -0
- package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-login-expired.json +31 -0
- package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-muted.json +31 -0
- package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-not-logged-in.json +14 -0
- package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-other.json +31 -0
- package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-rate-limited.json +31 -0
- package/skill/krillplayer-plugin/assets/samples/live-video-platform/cases/danmaku-send-sent.json +28 -0
- package/skill/krillplayer-plugin/assets/samples/live-video-platform/manifest.ts +2 -1
- package/skill/krillplayer-plugin/assets/samples/live-video-platform/plugin.ts +40 -1
- package/skill/krillplayer-plugin/references/contract.d.ts +21 -14
package/dist/cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//
|
|
1
|
+
// package/cli.ts
|
|
2
2
|
import { execFile as execFile2 } from "node:child_process";
|
|
3
3
|
import { existsSync, readFileSync } from "node:fs";
|
|
4
4
|
import { cp, mkdir as mkdir3, mkdtemp as mkdtemp2, readdir as readdir5, readFile as readFile6, rm as rm3, writeFile as writeFile3 } from "node:fs/promises";
|
|
@@ -8,7 +8,7 @@ import { basename as basename2, dirname as dirname2, join as join5, relative as
|
|
|
8
8
|
import { fileURLToPath as fileURLToPath3 } from "node:url";
|
|
9
9
|
import { parseArgs, promisify as promisify2 } from "node:util";
|
|
10
10
|
|
|
11
|
-
//
|
|
11
|
+
// contract/schema.ts
|
|
12
12
|
var string = { kind: "string" };
|
|
13
13
|
var integer = { kind: "integer" };
|
|
14
14
|
var number = { kind: "number" };
|
|
@@ -17,8 +17,8 @@ var bytes = { kind: "bytes" };
|
|
|
17
17
|
function constant(value) {
|
|
18
18
|
return { kind: "constant", value };
|
|
19
19
|
}
|
|
20
|
-
function enumeration(
|
|
21
|
-
return { kind: "enum", name, values, ...unknown === void 0 ? {} : { unknown } };
|
|
20
|
+
function enumeration(name2, values, unknown) {
|
|
21
|
+
return { kind: "enum", name: name2, values, ...unknown === void 0 ? {} : { unknown } };
|
|
22
22
|
}
|
|
23
23
|
function array(of) {
|
|
24
24
|
return { kind: "array", of };
|
|
@@ -29,21 +29,21 @@ function map(of) {
|
|
|
29
29
|
function optional(of) {
|
|
30
30
|
return { kind: "optional", of };
|
|
31
31
|
}
|
|
32
|
-
function object(
|
|
33
|
-
return { kind: "object", name, fields, ...swift === void 0 ? {} : { swift } };
|
|
32
|
+
function object(name2, fields, swift) {
|
|
33
|
+
return { kind: "object", name: name2, fields, ...swift === void 0 ? {} : { swift } };
|
|
34
34
|
}
|
|
35
|
-
function union(
|
|
35
|
+
function union(name2, tag, variants, swift) {
|
|
36
36
|
const byValue = {};
|
|
37
37
|
for (const variant of variants) {
|
|
38
38
|
const value = variant.fields[tag].value;
|
|
39
|
-
if (byValue[value] !== void 0) throw new Error(`union ${
|
|
39
|
+
if (byValue[value] !== void 0) throw new Error(`union ${name2} has two variants tagged ${value}`);
|
|
40
40
|
byValue[value] = variant;
|
|
41
41
|
}
|
|
42
|
-
return { kind: "union", name, tag, variants: byValue, wrapped: false, ...swift === void 0 ? {} : { swift } };
|
|
42
|
+
return { kind: "union", name: name2, tag, variants: byValue, wrapped: false, ...swift === void 0 ? {} : { swift } };
|
|
43
43
|
}
|
|
44
|
-
function wrapped(
|
|
45
|
-
if (tag in variants) throw new Error(`union ${
|
|
46
|
-
return { kind: "union", name, tag, variants, wrapped: true };
|
|
44
|
+
function wrapped(name2, tag, variants) {
|
|
45
|
+
if (tag in variants) throw new Error(`union ${name2} cannot have a variant named like its tag ${tag}`);
|
|
46
|
+
return { kind: "union", name: name2, tag, variants, wrapped: true };
|
|
47
47
|
}
|
|
48
48
|
var pages = /* @__PURE__ */ new Map();
|
|
49
49
|
function paged(of) {
|
|
@@ -55,7 +55,7 @@ function paged(of) {
|
|
|
55
55
|
return page;
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
-
//
|
|
58
|
+
// contract/contract.ts
|
|
59
59
|
var CONTRACT = { interfaceLevel: 0, revision: 2 };
|
|
60
60
|
var STORAGE_LIMITS = { keyBytes: 256, valueBytes: 64 * 1024, pluginBytes: 1024 * 1024 };
|
|
61
61
|
var RUNTIME_LIMITS = { memoryBytes: 64 * 1024 * 1024, callSeconds: 20, stackBytes: 256 * 1024, callDepth: 64 };
|
|
@@ -79,7 +79,8 @@ var Capability = enumeration("Capability", [
|
|
|
79
79
|
"login",
|
|
80
80
|
"playbackReport",
|
|
81
81
|
"views",
|
|
82
|
-
"libraryChanges"
|
|
82
|
+
"libraryChanges",
|
|
83
|
+
"danmakuSend"
|
|
83
84
|
]);
|
|
84
85
|
var Media = enumeration("Media", ["video", "audio"]);
|
|
85
86
|
var ChannelKind = enumeration("ChannelKind", ["creator", "station", "podcast"]);
|
|
@@ -389,6 +390,9 @@ var PluginErrorKind = enumeration("PluginErrorKind", [
|
|
|
389
390
|
"refused",
|
|
390
391
|
"retryable",
|
|
391
392
|
"notFound",
|
|
393
|
+
"muted",
|
|
394
|
+
"rateLimited",
|
|
395
|
+
"contentRejected",
|
|
392
396
|
"other"
|
|
393
397
|
], "other");
|
|
394
398
|
var PluginError = object("PluginError", {
|
|
@@ -794,11 +798,12 @@ var SLOT_RULES = {
|
|
|
794
798
|
pairs: [],
|
|
795
799
|
capabilities: { subtitles: ["list"], subtitleSearch: ["search"] }
|
|
796
800
|
},
|
|
801
|
+
// send 是在直播间里发一条弹幕(contract.md 2.7),单独一项能力:只认 danmaku 的旧内核不认识 danmakuSend,跳过,不会去调它。
|
|
797
802
|
danmaku: {
|
|
798
|
-
functions: ["connect", "decode", "segment", "match", "comments"],
|
|
803
|
+
functions: ["connect", "decode", "segment", "match", "comments", "send"],
|
|
799
804
|
required: [],
|
|
800
805
|
pairs: [["connect", "decode"], ["match", "comments"]],
|
|
801
|
-
capabilities: { danmaku: ["connect", "segment"], danmakuMatch: ["match"] }
|
|
806
|
+
capabilities: { danmaku: ["connect", "segment"], danmakuMatch: ["match"], danmakuSend: ["send"] }
|
|
802
807
|
},
|
|
803
808
|
status: { functions: ["check", "images"], required: ["check"], pairs: [], capabilities: { status: ["check"] } },
|
|
804
809
|
login: {
|
|
@@ -856,19 +861,19 @@ var SLOT_RETURNS = {
|
|
|
856
861
|
resolve: { "": { schema: Resolved, nullable: true } }
|
|
857
862
|
};
|
|
858
863
|
var TOP_LEVEL_FUNCTIONS = { resolve: "resolve" };
|
|
859
|
-
function slotMember(slot,
|
|
864
|
+
function slotMember(slot, name2) {
|
|
860
865
|
if (typeof slot !== "object" && typeof slot !== "function" || slot === null) return void 0;
|
|
861
|
-
const descriptor = Object.getOwnPropertyDescriptor(slot,
|
|
866
|
+
const descriptor = Object.getOwnPropertyDescriptor(slot, name2);
|
|
862
867
|
return descriptor !== void 0 && "value" in descriptor ? descriptor.value : void 0;
|
|
863
868
|
}
|
|
864
869
|
|
|
865
|
-
//
|
|
870
|
+
// packer/pack.ts
|
|
866
871
|
import { build as build2 } from "esbuild";
|
|
867
872
|
import { mkdir as mkdir2, readdir as readdir4, readFile as readFile5, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
|
|
868
873
|
import { join as join4 } from "node:path";
|
|
869
874
|
import { fileURLToPath as fileURLToPath2, pathToFileURL } from "node:url";
|
|
870
875
|
|
|
871
|
-
//
|
|
876
|
+
// contract/not-yet-used.ts
|
|
872
877
|
var NOT_YET_USED = [
|
|
873
878
|
"Album.compilation",
|
|
874
879
|
"Album.count",
|
|
@@ -886,19 +891,9 @@ var NOT_YET_USED = [
|
|
|
886
891
|
"ArtistPage.artist",
|
|
887
892
|
"ArtistRef.image",
|
|
888
893
|
"BoxSet.ancestors",
|
|
889
|
-
"ChannelImage.id",
|
|
890
|
-
"ChannelImage.image",
|
|
891
894
|
"ChannelRef.image",
|
|
892
895
|
"ChannelRef.kind",
|
|
893
|
-
"ChannelStatus.id",
|
|
894
896
|
"ChannelStatus.latest",
|
|
895
|
-
"ChannelStatus.live",
|
|
896
|
-
"ChannelStatus.liveId",
|
|
897
|
-
"ChannelStatus.offlineReason",
|
|
898
|
-
"ChannelStatus.retryAfter",
|
|
899
|
-
"ChannelStatus.session",
|
|
900
|
-
"ChannelStatus.title",
|
|
901
|
-
"ChannelStatus.unknownReason",
|
|
902
897
|
"CollectionRef.kind",
|
|
903
898
|
"CommentGift.count",
|
|
904
899
|
"CommentGift.name",
|
|
@@ -975,12 +970,10 @@ var NOT_YET_USED = [
|
|
|
975
970
|
"VersionInfo.bitDepth",
|
|
976
971
|
"VersionInfo.languages",
|
|
977
972
|
"VersionInfo.sampleRate",
|
|
978
|
-
"resolve"
|
|
979
|
-
"status.check",
|
|
980
|
-
"status.images"
|
|
973
|
+
"resolve"
|
|
981
974
|
];
|
|
982
975
|
|
|
983
|
-
//
|
|
976
|
+
// host/i18n.ts
|
|
984
977
|
var DICTIONARY_BYTES = 256 * 1024;
|
|
985
978
|
function parseTag(text) {
|
|
986
979
|
const parts = text.replaceAll("_", "-").split("-");
|
|
@@ -1048,9 +1041,9 @@ function pieces(template) {
|
|
|
1048
1041
|
}
|
|
1049
1042
|
if (character === "{") {
|
|
1050
1043
|
const end = template.indexOf("}", index + 1);
|
|
1051
|
-
const
|
|
1052
|
-
if (
|
|
1053
|
-
result.push({ text: literal }, { name });
|
|
1044
|
+
const name2 = end < 0 ? "" : template.slice(index + 1, end);
|
|
1045
|
+
if (name2 !== "" && !name2.includes("{")) {
|
|
1046
|
+
result.push({ text: literal }, { name: name2 });
|
|
1054
1047
|
literal = "";
|
|
1055
1048
|
index = end;
|
|
1056
1049
|
continue;
|
|
@@ -1086,11 +1079,11 @@ function translate({ locale, language, dictionaries: dictionaries2 }, text, valu
|
|
|
1086
1079
|
return fill(lookup(dictionaries2, locale, language, text, context), values, locale);
|
|
1087
1080
|
}
|
|
1088
1081
|
|
|
1089
|
-
//
|
|
1082
|
+
// trial-runner/trial.ts
|
|
1090
1083
|
import { readdir as readdir3, readFile as readFile4, writeFile } from "node:fs/promises";
|
|
1091
1084
|
import { basename, join as join3, resolve } from "node:path";
|
|
1092
1085
|
|
|
1093
|
-
//
|
|
1086
|
+
// host/files.ts
|
|
1094
1087
|
var FileServiceError = class extends Error {
|
|
1095
1088
|
failure;
|
|
1096
1089
|
constructor(failure2) {
|
|
@@ -1166,7 +1159,7 @@ function createFiles(host) {
|
|
|
1166
1159
|
};
|
|
1167
1160
|
}
|
|
1168
1161
|
|
|
1169
|
-
//
|
|
1162
|
+
// host/network.ts
|
|
1170
1163
|
var MAX_REDIRECTS = 20;
|
|
1171
1164
|
var REMEMBERED_HOSTS = 8;
|
|
1172
1165
|
var REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
|
|
@@ -1257,9 +1250,9 @@ function restrictedAddress(address, sharedSpace = false) {
|
|
|
1257
1250
|
return (v6[0] & 254) === 252 || v6[0] === 254 && (v6[1] & 192) === 128;
|
|
1258
1251
|
}
|
|
1259
1252
|
function localHost(host, sharedSpace = false) {
|
|
1260
|
-
const
|
|
1261
|
-
if (
|
|
1262
|
-
return restrictedAddress(
|
|
1253
|
+
const name2 = bareHost(host);
|
|
1254
|
+
if (name2 === "localhost" || name2.endsWith(".localhost") || name2.endsWith(".local")) return true;
|
|
1255
|
+
return restrictedAddress(name2, sharedSpace);
|
|
1263
1256
|
}
|
|
1264
1257
|
function parseIPv4(text) {
|
|
1265
1258
|
const parts = text.split(".");
|
|
@@ -1375,8 +1368,8 @@ var Chain = class {
|
|
|
1375
1368
|
throw this.refuse("login-page", address, `${this.label(address)} is not declared in the plugin manifest`);
|
|
1376
1369
|
}
|
|
1377
1370
|
this.startsAtUserAddress = (this.grants.userAddresses ?? []).some((value) => normalForm(value)?.href === address.href);
|
|
1378
|
-
const
|
|
1379
|
-
return this.settle({ address, hostClass, method, headers, body: request.body === true, frames: request.frames });
|
|
1371
|
+
const headers2 = remembered ? only(request.headers ?? {}, SAFELIST) : { ...request.headers };
|
|
1372
|
+
return this.settle({ address, hostClass, method, headers: headers2, body: request.body === true, frames: request.frames });
|
|
1380
1373
|
}
|
|
1381
1374
|
// 上一跳回了跳转。方法、请求体、请求头按上一跳的状态码与两跳的关系改写。
|
|
1382
1375
|
redirect(status, location) {
|
|
@@ -1389,7 +1382,7 @@ var Chain = class {
|
|
|
1389
1382
|
const becomesGet = status === 303 ? previous.method !== "GET" && previous.method !== "HEAD" : (status === 301 || status === 302) && previous.method === "POST";
|
|
1390
1383
|
const method = becomesGet ? "GET" : previous.method;
|
|
1391
1384
|
const body = becomesGet ? false : previous.body;
|
|
1392
|
-
let
|
|
1385
|
+
let headers2 = becomesGet ? without(previous.headers, BODY_HEADERS) : previous.headers;
|
|
1393
1386
|
if (this.seen.has(`${method} ${address.href}`)) throw this.refuse("redirect-loop", address, `redirect loop at ${this.label(address)}`);
|
|
1394
1387
|
const downgrade = previous.address.scheme === "https" && address.scheme === "http";
|
|
1395
1388
|
if (downgrade && this.use !== "playback-follow" && this.use !== "playback-probe") {
|
|
@@ -1403,9 +1396,9 @@ var Chain = class {
|
|
|
1403
1396
|
const upgrade = hostClass === "user" && address.host === previous.address.host && previous.address.scheme === "http" && address.scheme === "https";
|
|
1404
1397
|
if (this.leftOrigin || address.origin !== previous.address.origin && !upgrade) {
|
|
1405
1398
|
this.leftOrigin = true;
|
|
1406
|
-
|
|
1399
|
+
headers2 = hostClass === "derived" ? only(headers2, SAFELIST) : this.withoutCredentials(headers2);
|
|
1407
1400
|
}
|
|
1408
|
-
return this.settle({ address, hostClass, method, headers, body });
|
|
1401
|
+
return this.settle({ address, hostClass, method, headers: headers2, body });
|
|
1409
1402
|
}
|
|
1410
1403
|
// 主机解析出的地址。解析不出(空)算连不上,不是这里的事。
|
|
1411
1404
|
resolved(addresses) {
|
|
@@ -1488,7 +1481,7 @@ var Chain = class {
|
|
|
1488
1481
|
return "only network stream addresses are allowed";
|
|
1489
1482
|
}
|
|
1490
1483
|
}
|
|
1491
|
-
settle({ address, hostClass, method, headers, body, frames }) {
|
|
1484
|
+
settle({ address, hostClass, method, headers: headers2, body, frames }) {
|
|
1492
1485
|
if (hostClass === "derived") {
|
|
1493
1486
|
if (method !== "GET" && method !== "HEAD" || body) {
|
|
1494
1487
|
throw this.refuse(
|
|
@@ -1497,14 +1490,14 @@ var Chain = class {
|
|
|
1497
1490
|
`${address.host} is neither declared nor given by the user, so only GET and HEAD without a body may be sent to it`
|
|
1498
1491
|
);
|
|
1499
1492
|
}
|
|
1500
|
-
const carried = [address.href, ...Object.keys(
|
|
1493
|
+
const carried = [address.href, ...Object.keys(headers2), ...Object.values(headers2), ...frames ?? []];
|
|
1501
1494
|
if (this.secrets.some((secret) => carried.some((text) => carries(text, secret)))) {
|
|
1502
1495
|
throw this.refuse("derived-no-secrets", address, `credentials may not be sent to ${address.host}, a host that is neither declared nor given by the user`);
|
|
1503
1496
|
}
|
|
1504
1497
|
}
|
|
1505
1498
|
const publicOnly = this.publicOnly(hostClass);
|
|
1506
1499
|
if (publicOnly !== null && localHost(address.host, publicOnly.sharedSpace)) throw this.privateAddress(address, "is");
|
|
1507
|
-
const pass = { hostClass, address, method, headers, body, challenge: !this.leftOrigin, publicOnly };
|
|
1500
|
+
const pass = { hostClass, address, method, headers: headers2, body, challenge: !this.leftOrigin, publicOnly };
|
|
1508
1501
|
this.seen.add(`${method} ${address.href}`);
|
|
1509
1502
|
this.current = pass;
|
|
1510
1503
|
return pass;
|
|
@@ -1518,15 +1511,15 @@ var Chain = class {
|
|
|
1518
1511
|
privateAddress(address, verb = "resolves to") {
|
|
1519
1512
|
return this.refuse("public-address", address, `${this.label(address)} ${verb} a private, loopback or link-local address`);
|
|
1520
1513
|
}
|
|
1521
|
-
withoutCredentials(
|
|
1522
|
-
return Object.fromEntries(Object.entries(
|
|
1514
|
+
withoutCredentials(headers2) {
|
|
1515
|
+
return Object.fromEntries(Object.entries(headers2).filter(([name2, value]) => !CREDENTIAL_HEADERS.has(name2.toLowerCase()) && !this.secrets.some((secret) => carries(name2, secret) || carries(value, secret))));
|
|
1523
1516
|
}
|
|
1524
1517
|
refuse(rule, address, message) {
|
|
1525
1518
|
return new NetworkRefusal(PREFIX[this.use], rule, address.host, message);
|
|
1526
1519
|
}
|
|
1527
1520
|
};
|
|
1528
|
-
var only = (
|
|
1529
|
-
var without = (
|
|
1521
|
+
var only = (headers2, names) => Object.fromEntries(Object.entries(headers2).filter(([name2]) => names.has(name2.toLowerCase())));
|
|
1522
|
+
var without = (headers2, names) => Object.fromEntries(Object.entries(headers2).filter(([name2]) => !names.has(name2.toLowerCase())));
|
|
1530
1523
|
function imageAddress(text, userHosts) {
|
|
1531
1524
|
const address = normalForm(text);
|
|
1532
1525
|
if (address === null || address.scheme !== "http" && address.scheme !== "https") return null;
|
|
@@ -1537,7 +1530,7 @@ function imageAddress(text, userHosts) {
|
|
|
1537
1530
|
return url.href;
|
|
1538
1531
|
}
|
|
1539
1532
|
|
|
1540
|
-
//
|
|
1533
|
+
// host/formats.ts
|
|
1541
1534
|
var isSpace = (c) => c === " " || c === " " || c === "\n" || c === "\r";
|
|
1542
1535
|
function trimSpace(text) {
|
|
1543
1536
|
let start = 0;
|
|
@@ -1555,9 +1548,9 @@ function textOf(data) {
|
|
|
1555
1548
|
var NAMED_ENTITIES = /* @__PURE__ */ new Map([["lt", "<"], ["gt", ">"], ["amp", "&"], ["quot", '"'], ["apos", "'"]]);
|
|
1556
1549
|
function decodeEntities(text) {
|
|
1557
1550
|
if (!text.includes("&")) return text;
|
|
1558
|
-
return text.replace(/&(#[xX][0-9a-fA-F]{1,8}|#[0-9]{1,8}|[A-Za-z][A-Za-z0-9]{0,31});/g, (whole,
|
|
1559
|
-
if (
|
|
1560
|
-
const code =
|
|
1551
|
+
return text.replace(/&(#[xX][0-9a-fA-F]{1,8}|#[0-9]{1,8}|[A-Za-z][A-Za-z0-9]{0,31});/g, (whole, name2) => {
|
|
1552
|
+
if (name2[0] !== "#") return NAMED_ENTITIES.get(name2) ?? whole;
|
|
1553
|
+
const code = name2[1] === "x" || name2[1] === "X" ? parseInt(name2.slice(2), 16) : parseInt(name2.slice(1), 10);
|
|
1561
1554
|
if (code <= 0 || code > 1114111 || code >= 55296 && code <= 57343) return whole;
|
|
1562
1555
|
return String.fromCodePoint(code);
|
|
1563
1556
|
});
|
|
@@ -1631,10 +1624,10 @@ function scanXML(text, onChild) {
|
|
|
1631
1624
|
} else if (text[i + 1] === "/") {
|
|
1632
1625
|
const end = text.indexOf(">", i + 2);
|
|
1633
1626
|
if (end === -1) break;
|
|
1634
|
-
const
|
|
1627
|
+
const name2 = trimSpace(text.slice(i + 2, end));
|
|
1635
1628
|
i = end + 1;
|
|
1636
1629
|
for (let index = stack.length - 1; index >= 0; index -= 1) {
|
|
1637
|
-
if (stack[index].name ===
|
|
1630
|
+
if (stack[index].name === name2) {
|
|
1638
1631
|
close(index);
|
|
1639
1632
|
break;
|
|
1640
1633
|
}
|
|
@@ -1668,7 +1661,7 @@ function scanXML(text, onChild) {
|
|
|
1668
1661
|
j += 1;
|
|
1669
1662
|
continue;
|
|
1670
1663
|
}
|
|
1671
|
-
const
|
|
1664
|
+
const name2 = text.slice(nameStart, j);
|
|
1672
1665
|
while (j < n && isSpace(text[j])) j += 1;
|
|
1673
1666
|
let value = "";
|
|
1674
1667
|
if (text[j] === "=") {
|
|
@@ -1685,7 +1678,7 @@ function scanXML(text, onChild) {
|
|
|
1685
1678
|
value = text.slice(valueStart, j);
|
|
1686
1679
|
}
|
|
1687
1680
|
}
|
|
1688
|
-
element.attributes[
|
|
1681
|
+
element.attributes[name2] = decodeEntities(value);
|
|
1689
1682
|
}
|
|
1690
1683
|
}
|
|
1691
1684
|
if (!closed) break;
|
|
@@ -1699,9 +1692,9 @@ function scanXML(text, onChild) {
|
|
|
1699
1692
|
close(0);
|
|
1700
1693
|
return root;
|
|
1701
1694
|
}
|
|
1702
|
-
var child = (element,
|
|
1703
|
-
function childText(element,
|
|
1704
|
-
const found = child(element,
|
|
1695
|
+
var child = (element, name2) => element.children.find((item) => item.name === name2);
|
|
1696
|
+
function childText(element, name2) {
|
|
1697
|
+
const found = child(element, name2);
|
|
1705
1698
|
if (found === void 0) return void 0;
|
|
1706
1699
|
const text = trimSpace(found.text);
|
|
1707
1700
|
return text === "" ? void 0 : text;
|
|
@@ -1821,7 +1814,7 @@ var VLC_HEADERS = /* @__PURE__ */ new Map([["http-user-agent", "User-Agent"], ["
|
|
|
1821
1814
|
function parseM3U(data) {
|
|
1822
1815
|
const playlist = { guideURLs: [], attributes: {}, entries: [] };
|
|
1823
1816
|
let info;
|
|
1824
|
-
let
|
|
1817
|
+
let headers2 = /* @__PURE__ */ new Map();
|
|
1825
1818
|
let group;
|
|
1826
1819
|
for (const raw of splitLines(textOf(data))) {
|
|
1827
1820
|
const line = trimSpace(raw);
|
|
@@ -1837,17 +1830,17 @@ function parseM3U(data) {
|
|
|
1837
1830
|
tvgName,
|
|
1838
1831
|
logo: nonEmpty(attributes.get("tvg-logo")),
|
|
1839
1832
|
group: nonEmpty(attributes.get("group-title")) ?? group,
|
|
1840
|
-
headers:
|
|
1833
|
+
headers: headers2.size === 0 ? void 0 : Object.fromEntries(headers2),
|
|
1841
1834
|
attributes: Object.fromEntries(attributes)
|
|
1842
1835
|
}));
|
|
1843
1836
|
info = void 0;
|
|
1844
|
-
|
|
1837
|
+
headers2 = /* @__PURE__ */ new Map();
|
|
1845
1838
|
group = void 0;
|
|
1846
1839
|
continue;
|
|
1847
1840
|
}
|
|
1848
|
-
const
|
|
1849
|
-
const directive = asciiLower(
|
|
1850
|
-
const value = line[
|
|
1841
|
+
const name2 = /^[^: \t]*/.exec(line)[0];
|
|
1842
|
+
const directive = asciiLower(name2);
|
|
1843
|
+
const value = line[name2.length] === ":" ? line.slice(name2.length + 1) : line.slice(name2.length);
|
|
1851
1844
|
if (directive === "#extm3u") {
|
|
1852
1845
|
const { attributes } = readAttributes(value);
|
|
1853
1846
|
playlist.attributes = { ...playlist.attributes, ...Object.fromEntries(attributes) };
|
|
@@ -1864,9 +1857,9 @@ function parseM3U(data) {
|
|
|
1864
1857
|
info = { duration: Number.isFinite(seconds) ? seconds : -1, attributes, title: trimSpace(rest ?? "") };
|
|
1865
1858
|
} else if (directive === "#extvlcopt") {
|
|
1866
1859
|
const equals = value.indexOf("=");
|
|
1867
|
-
const
|
|
1860
|
+
const name3 = VLC_HEADERS.get(asciiLower(trimSpace(equals === -1 ? value : value.slice(0, equals))));
|
|
1868
1861
|
const headerValue = equals === -1 ? "" : trimSpace(value.slice(equals + 1));
|
|
1869
|
-
if (
|
|
1862
|
+
if (name3 !== void 0 && headerValue !== "") headers2.set(name3, headerValue);
|
|
1870
1863
|
} else if (directive === "#extgrp") {
|
|
1871
1864
|
group = nonEmpty(value);
|
|
1872
1865
|
}
|
|
@@ -1881,8 +1874,8 @@ function parseXML(data) {
|
|
|
1881
1874
|
}
|
|
1882
1875
|
function withNamespaces(element, inherited) {
|
|
1883
1876
|
let scope = inherited;
|
|
1884
|
-
for (const [
|
|
1885
|
-
const prefix2 =
|
|
1877
|
+
for (const [name2, value] of Object.entries(element.attributes)) {
|
|
1878
|
+
const prefix2 = name2 === "xmlns" ? "" : name2.startsWith("xmlns:") ? name2.slice(6) : void 0;
|
|
1886
1879
|
if (prefix2 === void 0 || prefix2 === "xml") continue;
|
|
1887
1880
|
if (scope === inherited) scope = new Map(inherited);
|
|
1888
1881
|
if (value === "") scope.delete(prefix2);
|
|
@@ -1946,7 +1939,7 @@ function parseXMLTV(data) {
|
|
|
1946
1939
|
if (id === void 0) return;
|
|
1947
1940
|
guide.channels.push(compact({
|
|
1948
1941
|
id,
|
|
1949
|
-
names: element.children.filter((item) => item.name === "display-name").map((item) => trimSpace(item.text)).filter((
|
|
1942
|
+
names: element.children.filter((item) => item.name === "display-name").map((item) => trimSpace(item.text)).filter((name2) => name2 !== ""),
|
|
1950
1943
|
icon: nonEmpty(child(element, "icon")?.attributes.src)
|
|
1951
1944
|
}));
|
|
1952
1945
|
} else if (element.name === "programme") {
|
|
@@ -1961,7 +1954,7 @@ function parseXMLTV(data) {
|
|
|
1961
1954
|
title: childText(element, "title") ?? "",
|
|
1962
1955
|
subtitle: childText(element, "sub-title"),
|
|
1963
1956
|
description: childText(element, "desc"),
|
|
1964
|
-
categories: element.children.filter((item) => item.name === "category").map((item) => trimSpace(item.text)).filter((
|
|
1957
|
+
categories: element.children.filter((item) => item.name === "category").map((item) => trimSpace(item.text)).filter((name2) => name2 !== ""),
|
|
1965
1958
|
icon: nonEmpty(child(element, "icon")?.attributes.src)
|
|
1966
1959
|
}));
|
|
1967
1960
|
}
|
|
@@ -1977,7 +1970,7 @@ function programmesIn(guide, query) {
|
|
|
1977
1970
|
});
|
|
1978
1971
|
}
|
|
1979
1972
|
|
|
1980
|
-
//
|
|
1973
|
+
// host/metadata.ts
|
|
1981
1974
|
var MetadataError = class extends Error {
|
|
1982
1975
|
failure;
|
|
1983
1976
|
constructor(failure2) {
|
|
@@ -2005,13 +1998,13 @@ function checkSearch(query, year) {
|
|
|
2005
1998
|
if (year !== void 0) checkYear(year);
|
|
2006
1999
|
return trimmed;
|
|
2007
2000
|
}
|
|
2008
|
-
function checkList(
|
|
2009
|
-
if (
|
|
2010
|
-
throw invalid(`${
|
|
2001
|
+
function checkList(name2, kind, { genre, country, year }) {
|
|
2002
|
+
if (name2 === "upcoming" && kind === "series" || name2 === "onAir" && kind === "movie") {
|
|
2003
|
+
throw invalid(`${name2} has no ${kind} list`);
|
|
2011
2004
|
}
|
|
2012
2005
|
const filtered = genre !== void 0 || country !== void 0 || year !== void 0;
|
|
2013
|
-
if (
|
|
2014
|
-
if (filtered) throw invalid(`${
|
|
2006
|
+
if (name2 !== "popular" && name2 !== "topRated") {
|
|
2007
|
+
if (filtered) throw invalid(`${name2} cannot be filtered`);
|
|
2015
2008
|
return;
|
|
2016
2009
|
}
|
|
2017
2010
|
if (genre !== void 0 && !GENRES[kind].has(genre)) throw invalid(`genre ${genre} has no ${kind} list`);
|
|
@@ -2033,16 +2026,16 @@ function optionsOf(value, allowed, fn) {
|
|
|
2033
2026
|
if (unknown !== void 0) throw fail(`krillplayer.metadata.${fn}: unknown option ${unknown}`);
|
|
2034
2027
|
return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== null && entry !== void 0));
|
|
2035
2028
|
}
|
|
2036
|
-
function integerOf(value,
|
|
2029
|
+
function integerOf(value, name2) {
|
|
2037
2030
|
if (value === void 0) return void 0;
|
|
2038
2031
|
if (typeof value !== "number" || !Number.isInteger(value) || Math.abs(value) >= 1e9) {
|
|
2039
|
-
throw fail(`krillplayer.metadata: ${
|
|
2032
|
+
throw fail(`krillplayer.metadata: ${name2} must be an integer`);
|
|
2040
2033
|
}
|
|
2041
2034
|
return value;
|
|
2042
2035
|
}
|
|
2043
|
-
function textOf2(value,
|
|
2036
|
+
function textOf2(value, name2) {
|
|
2044
2037
|
if (value === void 0) return void 0;
|
|
2045
|
-
if (typeof value !== "string") throw fail(`krillplayer.metadata: ${
|
|
2038
|
+
if (typeof value !== "string") throw fail(`krillplayer.metadata: ${name2} must be a string`);
|
|
2046
2039
|
return value;
|
|
2047
2040
|
}
|
|
2048
2041
|
var optional2 = (key, value) => value === void 0 ? {} : { [key]: value };
|
|
@@ -2092,9 +2085,9 @@ function createMetadata(service) {
|
|
|
2092
2085
|
}
|
|
2093
2086
|
return run2(() => metadata.work(checkedKind, values));
|
|
2094
2087
|
},
|
|
2095
|
-
async list(
|
|
2088
|
+
async list(name2, kind, options) {
|
|
2096
2089
|
const metadata = available();
|
|
2097
|
-
if (typeof
|
|
2090
|
+
if (typeof name2 !== "string" || !ListName.values.includes(name2)) {
|
|
2098
2091
|
throw fail(`krillplayer.metadata.list needs a list name: ${ListName.values.join(", ")}`);
|
|
2099
2092
|
}
|
|
2100
2093
|
const checkedKind = kindOf(kind);
|
|
@@ -2109,12 +2102,12 @@ function createMetadata(service) {
|
|
|
2109
2102
|
...optional2("year", integerOf(fields.year, "year"))
|
|
2110
2103
|
};
|
|
2111
2104
|
const cursor = textOf2(fields.cursor, "cursor");
|
|
2112
|
-
return run2(() => metadata.list(
|
|
2105
|
+
return run2(() => metadata.list(name2, checkedKind, filter, cursor));
|
|
2113
2106
|
}
|
|
2114
2107
|
};
|
|
2115
2108
|
}
|
|
2116
2109
|
|
|
2117
|
-
//
|
|
2110
|
+
// host/json-depth.ts
|
|
2118
2111
|
function pluginJSONText(bytes2) {
|
|
2119
2112
|
if (bytes2[0] === 239 && bytes2[1] === 187 && bytes2[2] === 191) return void 0;
|
|
2120
2113
|
if (bytes2.includes(0)) return void 0;
|
|
@@ -2145,7 +2138,7 @@ function nestedTooDeep(json, limit = VALUE_LIMITS.depth) {
|
|
|
2145
2138
|
return false;
|
|
2146
2139
|
}
|
|
2147
2140
|
|
|
2148
|
-
//
|
|
2141
|
+
// host/crypto.ts
|
|
2149
2142
|
var RSA = ["RSASSA-PKCS1-v1_5", "RSA-PSS", "RSA-OAEP"];
|
|
2150
2143
|
var AES = ["AES-CTR", "AES-CBC", "AES-GCM"];
|
|
2151
2144
|
var SIGNING = ["RSASSA-PKCS1-v1_5", "RSA-PSS", "ECDSA", "Ed25519", "HMAC"];
|
|
@@ -2155,7 +2148,7 @@ var KDF = ["HKDF", "PBKDF2"];
|
|
|
2155
2148
|
var AGREEMENT = ["ECDH", "X25519"];
|
|
2156
2149
|
var WRAPPING = ["AES-KW", ...ENCRYPTION];
|
|
2157
2150
|
var SUPPORTED = {
|
|
2158
|
-
generateKey: CryptoAlgorithm.values.filter((
|
|
2151
|
+
generateKey: CryptoAlgorithm.values.filter((name2) => !KDF.includes(name2)),
|
|
2159
2152
|
importKey: CryptoAlgorithm.values,
|
|
2160
2153
|
exportKey: CryptoAlgorithm.values,
|
|
2161
2154
|
sign: SIGNING,
|
|
@@ -2184,9 +2177,9 @@ var USAGES = {
|
|
|
2184
2177
|
HKDF: { secret: ["deriveKey", "deriveBits"] },
|
|
2185
2178
|
PBKDF2: { secret: ["deriveKey", "deriveBits"] }
|
|
2186
2179
|
};
|
|
2187
|
-
var ktyOf = (
|
|
2180
|
+
var ktyOf = (name2) => RSA.includes(name2) ? "RSA" : name2 === "ECDSA" || name2 === "ECDH" ? "EC" : name2 === "Ed25519" || name2 === "X25519" ? "OKP" : "oct";
|
|
2188
2181
|
var ELLIPTIC = ["ECDSA", "ECDH"];
|
|
2189
|
-
var fixedCurve = (
|
|
2182
|
+
var fixedCurve = (name2) => name2 === "Ed25519" || name2 === "X25519" ? name2 : void 0;
|
|
2190
2183
|
var HASH_BYTES = { "SHA-1": 20, "SHA-256": 32, "SHA-384": 48, "SHA-512": 64 };
|
|
2191
2184
|
var HASH_BLOCK_BITS = { "SHA-1": 512, "SHA-256": 512, "SHA-384": 1024, "SHA-512": 1024 };
|
|
2192
2185
|
var COORDINATE_BYTES = { "P-256": 32, "P-384": 48, "P-521": 66 };
|
|
@@ -2267,20 +2260,20 @@ function algorithmOf(operation, algorithm, listing = operation) {
|
|
|
2267
2260
|
const params = typeof algorithm === "string" ? { name: algorithm } : isObject2(algorithm) ? algorithm : void 0;
|
|
2268
2261
|
if (params === void 0 || typeof params.name !== "string") throw fail2(operation, "algorithm needs a name");
|
|
2269
2262
|
const given = params.name;
|
|
2270
|
-
const
|
|
2271
|
-
if (
|
|
2272
|
-
return { name, params };
|
|
2263
|
+
const name2 = CryptoAlgorithm.values.find((value) => value.toLowerCase() === given.toLowerCase());
|
|
2264
|
+
if (name2 === void 0 || !SUPPORTED[listing].includes(name2)) throw fail2(operation, `${given} is not a supported algorithm for ${operation}`);
|
|
2265
|
+
return { name: name2, params };
|
|
2273
2266
|
}
|
|
2274
2267
|
function hashOf(operation, value, owner) {
|
|
2275
2268
|
const given = typeof value === "string" ? value : isObject2(value) && typeof value.name === "string" ? value.name : void 0;
|
|
2276
2269
|
if (given === void 0) throw fail2(operation, `${owner} needs hash`);
|
|
2277
|
-
const hash = CryptoHash.values.find((
|
|
2270
|
+
const hash = CryptoHash.values.find((name2) => name2.toLowerCase() === given.toLowerCase());
|
|
2278
2271
|
if (hash === void 0) throw fail2(operation, `${given} is not a supported hash (SHA-1, SHA-256, SHA-384, SHA-512)`);
|
|
2279
2272
|
return hash;
|
|
2280
2273
|
}
|
|
2281
2274
|
function curveOf(operation, value, owner) {
|
|
2282
2275
|
if (typeof value !== "string") throw fail2(operation, `${owner} needs namedCurve`);
|
|
2283
|
-
const curve = CryptoNamedCurve.values.find((
|
|
2276
|
+
const curve = CryptoNamedCurve.values.find((name2) => name2 === value);
|
|
2284
2277
|
if (curve === void 0) throw fail2(operation, `${value} is not a supported curve (P-256, P-384, P-521)`);
|
|
2285
2278
|
return curve;
|
|
2286
2279
|
}
|
|
@@ -2309,7 +2302,7 @@ function usagesOf(operation, value) {
|
|
|
2309
2302
|
return CryptoKeyUsage.values.filter((usage) => value.includes(usage));
|
|
2310
2303
|
}
|
|
2311
2304
|
function formatOf(operation, value) {
|
|
2312
|
-
const format2 = CryptoKeyFormat.values.find((
|
|
2305
|
+
const format2 = CryptoKeyFormat.values.find((name2) => name2 === value);
|
|
2313
2306
|
if (format2 === void 0) throw fail2(operation, `${typeof value === "string" ? value : "the format"} is not a key format (raw, spki, pkcs8, jwk)`);
|
|
2314
2307
|
return format2;
|
|
2315
2308
|
}
|
|
@@ -2319,46 +2312,46 @@ async function keyOf(operation, value, what = "key") {
|
|
|
2319
2312
|
const { type, extractable, algorithm, usages, material } = value;
|
|
2320
2313
|
if (type !== "secret" && type !== "public" && type !== "private") throw bad();
|
|
2321
2314
|
if (typeof extractable !== "boolean" || !Array.isArray(usages) || usages.some((usage) => !CryptoKeyUsage.values.includes(usage))) throw bad();
|
|
2322
|
-
const
|
|
2323
|
-
if (
|
|
2315
|
+
const name2 = CryptoAlgorithm.values.find((known) => known === algorithm.name);
|
|
2316
|
+
if (name2 === void 0 || typeof material.kty !== "string") throw bad();
|
|
2324
2317
|
if (!Object.values(material).every((field) => typeof field === "string") || !fieldsFit(material)) throw bad();
|
|
2325
2318
|
const hash = isObject2(algorithm.hash) ? CryptoHash.values.find((known) => known === algorithm.hash.name) : void 0;
|
|
2326
|
-
if ((RSA.includes(
|
|
2327
|
-
const expected = USAGES[
|
|
2319
|
+
if ((RSA.includes(name2) || name2 === "HMAC") && hash === void 0) throw bad();
|
|
2320
|
+
const expected = USAGES[name2][type];
|
|
2328
2321
|
if (expected === void 0 || usages.some((usage) => !expected.includes(usage))) throw bad();
|
|
2329
|
-
if (material.kty !== ktyOf(
|
|
2330
|
-
if (ELLIPTIC.includes(
|
|
2331
|
-
if (fixedCurve(
|
|
2332
|
-
if (KDF.includes(
|
|
2333
|
-
if (!usableMaterial(
|
|
2334
|
-
const derived = keyAlgorithm(
|
|
2322
|
+
if (material.kty !== ktyOf(name2) || type === "private" !== (material.d !== void 0)) throw bad();
|
|
2323
|
+
if (ELLIPTIC.includes(name2) && (!CryptoNamedCurve.values.includes(algorithm.namedCurve) || material.crv !== algorithm.namedCurve)) throw bad();
|
|
2324
|
+
if (fixedCurve(name2) !== void 0 && material.crv !== fixedCurve(name2)) throw bad();
|
|
2325
|
+
if (KDF.includes(name2) && extractable) throw bad();
|
|
2326
|
+
if (!usableMaterial(name2, type, material, algorithm.namedCurve)) throw bad();
|
|
2327
|
+
const derived = keyAlgorithm(name2, material, { hash, curve: algorithm.namedCurve });
|
|
2335
2328
|
if (!sameSize(algorithm.modulusLength, derived.modulusLength) || !sameSize(algorithm.length, derived.length)) throw bad();
|
|
2336
2329
|
const key = makeKey(type, extractable, derived, usages, material);
|
|
2337
2330
|
try {
|
|
2338
|
-
await webKey(key, USAGES[
|
|
2339
|
-
if (type === "private" && (ELLIPTIC.includes(
|
|
2331
|
+
await webKey(key, USAGES[name2][type][0]);
|
|
2332
|
+
if (type === "private" && (ELLIPTIC.includes(name2) || fixedCurve(name2) !== void 0)) await checkPair(key.material, name2, key.algorithm.namedCurve);
|
|
2340
2333
|
} catch {
|
|
2341
2334
|
throw bad();
|
|
2342
2335
|
}
|
|
2343
2336
|
return key;
|
|
2344
2337
|
}
|
|
2345
|
-
function usableMaterial(
|
|
2338
|
+
function usableMaterial(name2, type, material, curve) {
|
|
2346
2339
|
const size = (field) => fromBase64url(material[field])?.length;
|
|
2347
|
-
if (
|
|
2348
|
-
if (AES_KEYS.includes(
|
|
2349
|
-
if (KDF.includes(
|
|
2350
|
-
if (RSA.includes(
|
|
2340
|
+
if (name2 === "HMAC") return (size("k") ?? 0) > 0 && size("k") <= MAX_HMAC_BYTES;
|
|
2341
|
+
if (AES_KEYS.includes(name2)) return [16, 24, 32].includes(size("k") ?? 0);
|
|
2342
|
+
if (KDF.includes(name2)) return size("k") !== void 0 && size("k") <= MAX_DERIVE_BYTES;
|
|
2343
|
+
if (RSA.includes(name2)) {
|
|
2351
2344
|
const modulus = fromBase64url(material.n);
|
|
2352
2345
|
const parts = type === "private" ? PRIVATE_FIELDS : [];
|
|
2353
2346
|
return modulus !== void 0 && bitLength(modulus) >= 512 && (size("e") ?? 0) > 0 && parts.every((field) => size(field) !== void 0);
|
|
2354
2347
|
}
|
|
2355
|
-
const coordinate = ELLIPTIC.includes(
|
|
2356
|
-
const fields = [...ELLIPTIC.includes(
|
|
2348
|
+
const coordinate = ELLIPTIC.includes(name2) ? COORDINATE_BYTES[curve] : 32;
|
|
2349
|
+
const fields = [...ELLIPTIC.includes(name2) ? ["x", "y"] : ["x"], ...type === "private" ? ["d"] : []];
|
|
2357
2350
|
return fields.every((field) => size(field) === coordinate);
|
|
2358
2351
|
}
|
|
2359
2352
|
var sameSize = (given, derived) => derived === void 0 ? given === void 0 : given === derived;
|
|
2360
|
-
function checkKey(operation, key,
|
|
2361
|
-
if (key.algorithm.name !==
|
|
2353
|
+
function checkKey(operation, key, name2, usage) {
|
|
2354
|
+
if (key.algorithm.name !== name2) throw fail2(operation, `the key is ${article(key.algorithm.name)} ${key.algorithm.name} key, not ${name2}`);
|
|
2362
2355
|
if (!key.usages.includes(usage)) throw fail2(operation, `the key's usages do not include ${usage}`);
|
|
2363
2356
|
}
|
|
2364
2357
|
function requireType(operation, key, type) {
|
|
@@ -2383,14 +2376,14 @@ var stripZeros = (bytes2) => {
|
|
|
2383
2376
|
const first = bytes2.findIndex((byte) => byte !== 0);
|
|
2384
2377
|
return first < 0 ? new Uint8Array(0) : bytes2.slice(first);
|
|
2385
2378
|
};
|
|
2386
|
-
function keyAlgorithm(
|
|
2387
|
-
if (RSA.includes(
|
|
2388
|
-
return { name, modulusLength: bitLength(fromBase64url(material.n)), publicExponent: stripZeros(fromBase64url(material.e)), hash: { name: extra.hash } };
|
|
2379
|
+
function keyAlgorithm(name2, material, extra) {
|
|
2380
|
+
if (RSA.includes(name2)) {
|
|
2381
|
+
return { name: name2, modulusLength: bitLength(fromBase64url(material.n)), publicExponent: stripZeros(fromBase64url(material.e)), hash: { name: extra.hash } };
|
|
2389
2382
|
}
|
|
2390
|
-
if (ELLIPTIC.includes(
|
|
2391
|
-
if (
|
|
2392
|
-
if (AES_KEYS.includes(
|
|
2393
|
-
return { name };
|
|
2383
|
+
if (ELLIPTIC.includes(name2)) return { name: name2, namedCurve: extra.curve };
|
|
2384
|
+
if (name2 === "HMAC") return { name: name2, length: fromBase64url(material.k).length * 8, hash: { name: extra.hash } };
|
|
2385
|
+
if (AES_KEYS.includes(name2)) return { name: name2, length: fromBase64url(material.k).length * 8 };
|
|
2386
|
+
return { name: name2 };
|
|
2394
2387
|
}
|
|
2395
2388
|
var PRIVATE_FIELDS = ["d", "p", "q", "dp", "dq", "qi"];
|
|
2396
2389
|
var MATERIAL_FIELDS = ["kty", "crv", "x", "y", "n", "e", "d", "p", "q", "dp", "dq", "qi", "k"];
|
|
@@ -2401,9 +2394,9 @@ var publicMaterial = (material) => Object.fromEntries(Object.entries(material).f
|
|
|
2401
2394
|
function makeKey(type, extractable, algorithm, usages, material) {
|
|
2402
2395
|
return { type, extractable, algorithm, usages, material };
|
|
2403
2396
|
}
|
|
2404
|
-
function jwkAlg(
|
|
2397
|
+
function jwkAlg(name2, hash, bits, curve) {
|
|
2405
2398
|
const size = hash?.slice(4);
|
|
2406
|
-
switch (
|
|
2399
|
+
switch (name2) {
|
|
2407
2400
|
case "RSASSA-PKCS1-v1_5":
|
|
2408
2401
|
return `RS${size}`;
|
|
2409
2402
|
case "RSA-PSS":
|
|
@@ -2416,7 +2409,7 @@ function jwkAlg(name, hash, bits, curve) {
|
|
|
2416
2409
|
case "AES-CBC":
|
|
2417
2410
|
case "AES-GCM":
|
|
2418
2411
|
case "AES-KW":
|
|
2419
|
-
return `A${bits}${
|
|
2412
|
+
return `A${bits}${name2.slice(4)}`;
|
|
2420
2413
|
case "Ed25519":
|
|
2421
2414
|
return "Ed25519";
|
|
2422
2415
|
case "ECDSA":
|
|
@@ -2430,62 +2423,62 @@ function jwkAlg(name, hash, bits, curve) {
|
|
|
2430
2423
|
}
|
|
2431
2424
|
async function generateKey(algorithm, extractableValue, usagesValue) {
|
|
2432
2425
|
const operation = "generateKey";
|
|
2433
|
-
const { name, params } = algorithmOf(operation, algorithm);
|
|
2426
|
+
const { name: name2, params } = algorithmOf(operation, algorithm);
|
|
2434
2427
|
const extractable = extractableOf(operation, extractableValue);
|
|
2435
2428
|
const usages = usagesOf(operation, usagesValue);
|
|
2436
|
-
const allowed = Object.values(USAGES[
|
|
2429
|
+
const allowed = Object.values(USAGES[name2]).flat();
|
|
2437
2430
|
let hash;
|
|
2438
2431
|
let curve;
|
|
2439
|
-
if (RSA.includes(
|
|
2440
|
-
const modulusLength = integerOf2(operation, params, "modulusLength",
|
|
2441
|
-
const exponent = bytesParam(operation, params, "publicExponent",
|
|
2442
|
-
hash = hashOf(operation, params.hash,
|
|
2443
|
-
checkGeneratedUsages(operation,
|
|
2432
|
+
if (RSA.includes(name2)) {
|
|
2433
|
+
const modulusLength = integerOf2(operation, params, "modulusLength", name2);
|
|
2434
|
+
const exponent = bytesParam(operation, params, "publicExponent", name2);
|
|
2435
|
+
hash = hashOf(operation, params.hash, name2);
|
|
2436
|
+
checkGeneratedUsages(operation, name2, usages, allowed);
|
|
2444
2437
|
if (!RSA_MODULUS_LENGTHS.includes(modulusLength)) throw fail2(operation, `modulusLength must be 1024, 2048, 3072 or 4096, not ${modulusLength}`);
|
|
2445
2438
|
if (stripZeros(exponent).join() !== "1,0,1") throw fail2(operation, "publicExponent must be 65537 ([1, 0, 1])");
|
|
2446
|
-
} else if (ELLIPTIC.includes(
|
|
2447
|
-
curve = curveOf(operation, params.namedCurve,
|
|
2448
|
-
checkGeneratedUsages(operation,
|
|
2449
|
-
} else if (
|
|
2450
|
-
hash = hashOf(operation, params.hash,
|
|
2451
|
-
const length = params.length === void 0 ? HASH_BLOCK_BITS[hash] : integerOf2(operation, params, "length",
|
|
2452
|
-
checkGeneratedUsages(operation,
|
|
2439
|
+
} else if (ELLIPTIC.includes(name2)) {
|
|
2440
|
+
curve = curveOf(operation, params.namedCurve, name2);
|
|
2441
|
+
checkGeneratedUsages(operation, name2, usages, allowed);
|
|
2442
|
+
} else if (name2 === "HMAC") {
|
|
2443
|
+
hash = hashOf(operation, params.hash, name2);
|
|
2444
|
+
const length = params.length === void 0 ? HASH_BLOCK_BITS[hash] : integerOf2(operation, params, "length", name2);
|
|
2445
|
+
checkGeneratedUsages(operation, name2, usages, allowed);
|
|
2453
2446
|
if (length <= 0 || length % 8 !== 0) throw fail2(operation, `HMAC length must be a positive multiple of 8, not ${length}`);
|
|
2454
2447
|
if (length > MAX_HMAC_BYTES * 8) throw fail2(operation, `an HMAC key can be at most ${MAX_HMAC_BYTES * 8} bits, not ${length}`);
|
|
2455
|
-
return secretKey(operation,
|
|
2456
|
-
} else if (AES_KEYS.includes(
|
|
2457
|
-
const length = integerOf2(operation, params, "length",
|
|
2458
|
-
checkGeneratedUsages(operation,
|
|
2448
|
+
return secretKey(operation, name2, extractable, usages, globalThis.crypto.getRandomValues(new Uint8Array(length / 8)), hash);
|
|
2449
|
+
} else if (AES_KEYS.includes(name2)) {
|
|
2450
|
+
const length = integerOf2(operation, params, "length", name2);
|
|
2451
|
+
checkGeneratedUsages(operation, name2, usages, allowed);
|
|
2459
2452
|
if (![128, 192, 256].includes(length)) throw fail2(operation, `an AES key must be 128, 192 or 256 bits, not ${length}`);
|
|
2460
|
-
return secretKey(operation,
|
|
2453
|
+
return secretKey(operation, name2, extractable, usages, globalThis.crypto.getRandomValues(new Uint8Array(length / 8)));
|
|
2461
2454
|
} else {
|
|
2462
|
-
checkGeneratedUsages(operation,
|
|
2455
|
+
checkGeneratedUsages(operation, name2, usages, allowed);
|
|
2463
2456
|
}
|
|
2464
|
-
const privateUsages = usages.filter((usage) => USAGES[
|
|
2465
|
-
const publicUsages = usages.filter((usage) => USAGES[
|
|
2457
|
+
const privateUsages = usages.filter((usage) => USAGES[name2].private.includes(usage));
|
|
2458
|
+
const publicUsages = usages.filter((usage) => USAGES[name2].public.includes(usage));
|
|
2466
2459
|
if (privateUsages.length === 0) throw fail2(operation, "a private key needs at least one usage");
|
|
2467
2460
|
const generated = await subtle().generateKey(
|
|
2468
|
-
RSA.includes(
|
|
2461
|
+
RSA.includes(name2) ? { name: name2, modulusLength: integerOf2(operation, params, "modulusLength", name2), publicExponent: new Uint8Array([1, 0, 1]), hash } : ELLIPTIC.includes(name2) ? { name: name2, namedCurve: curve } : { name: name2 },
|
|
2469
2462
|
true,
|
|
2470
|
-
[...USAGES[
|
|
2463
|
+
[...USAGES[name2].private, ...USAGES[name2].public]
|
|
2471
2464
|
);
|
|
2472
2465
|
const material = materialOf(await subtle().exportKey("jwk", generated.privateKey));
|
|
2473
|
-
const keyAlg = keyAlgorithm(
|
|
2466
|
+
const keyAlg = keyAlgorithm(name2, material, { hash, curve });
|
|
2474
2467
|
return {
|
|
2475
2468
|
publicKey: makeKey("public", true, keyAlg, publicUsages, publicMaterial(material)),
|
|
2476
2469
|
privateKey: makeKey("private", extractable, keyAlg, privateUsages, material)
|
|
2477
2470
|
};
|
|
2478
2471
|
}
|
|
2479
|
-
function checkGeneratedUsages(operation,
|
|
2472
|
+
function checkGeneratedUsages(operation, name2, usages, allowed) {
|
|
2480
2473
|
const wrong = usages.find((usage) => !allowed.includes(usage));
|
|
2481
|
-
if (wrong !== void 0) throw fail2(operation, `${wrong} is not a usage of ${
|
|
2474
|
+
if (wrong !== void 0) throw fail2(operation, `${wrong} is not a usage of ${name2} keys`);
|
|
2482
2475
|
}
|
|
2483
|
-
function secretKey(operation,
|
|
2476
|
+
function secretKey(operation, name2, extractable, usages, bytes2, hash) {
|
|
2484
2477
|
if (usages.length === 0) throw fail2(operation, "a secret key needs at least one usage");
|
|
2485
2478
|
const material = { kty: "oct", k: base64url(bytes2) };
|
|
2486
|
-
return makeKey("secret", extractable, keyAlgorithm(
|
|
2479
|
+
return makeKey("secret", extractable, keyAlgorithm(name2, material, { hash }), usages, material);
|
|
2487
2480
|
}
|
|
2488
|
-
var IMPORT_FORMATS = (
|
|
2481
|
+
var IMPORT_FORMATS = (name2) => RSA.includes(name2) ? ["spki", "pkcs8", "jwk"] : KDF.includes(name2) ? ["raw"] : ELLIPTIC.includes(name2) || fixedCurve(name2) !== void 0 ? ["raw", "spki", "pkcs8", "jwk"] : ["raw", "jwk"];
|
|
2489
2482
|
function importKey(formatValue, keyData, algorithm, extractableValue, usagesValue) {
|
|
2490
2483
|
return importKeyAs("importKey", formatValue, keyData, algorithm, extractableValue, usagesValue);
|
|
2491
2484
|
}
|
|
@@ -2497,51 +2490,51 @@ async function importKeyAs(operation, formatValue, keyData, algorithm, extractab
|
|
|
2497
2490
|
const given = format2 === "jwk" ? void 0 : bytesArgument(operation, keyData, "keyData");
|
|
2498
2491
|
if (given !== void 0 && given.length > MAX_KEY_BYTES) throw fail2(operation, `keyData can be at most ${MAX_KEY_BYTES} bytes, not ${given.length}`);
|
|
2499
2492
|
const data = given === void 0 ? void 0 : fromPEM(operation, format2, given);
|
|
2500
|
-
const { name, params } = algorithmOf(operation, algorithm, "importKey");
|
|
2501
|
-
const hash = RSA.includes(
|
|
2502
|
-
const curve = ELLIPTIC.includes(
|
|
2503
|
-
const hmacLength =
|
|
2493
|
+
const { name: name2, params } = algorithmOf(operation, algorithm, "importKey");
|
|
2494
|
+
const hash = RSA.includes(name2) || name2 === "HMAC" ? hashOf(operation, params.hash, name2) : void 0;
|
|
2495
|
+
const curve = ELLIPTIC.includes(name2) ? curveOf(operation, params.namedCurve, name2) : void 0;
|
|
2496
|
+
const hmacLength = name2 === "HMAC" && params.length !== void 0 ? integerOf2(operation, params, "length", name2) : void 0;
|
|
2504
2497
|
const extractable = extractableOf(operation, extractableValue);
|
|
2505
2498
|
const usages = usagesOf(operation, usagesValue);
|
|
2506
|
-
if (!IMPORT_FORMATS(
|
|
2507
|
-
const symmetric =
|
|
2499
|
+
if (!IMPORT_FORMATS(name2).includes(format2)) throw fail2(operation, `${name2} keys cannot be imported as ${format2}`);
|
|
2500
|
+
const symmetric = name2 === "HMAC" || AES_KEYS.includes(name2) || KDF.includes(name2);
|
|
2508
2501
|
const type = symmetric ? "secret" : format2 === "pkcs8" || format2 === "jwk" && jwk.d !== void 0 ? "private" : "public";
|
|
2509
|
-
const wrong = usages.find((usage) => !USAGES[
|
|
2510
|
-
if (wrong !== void 0) throw fail2(operation, `${wrong} is not a usage of a ${type} ${
|
|
2511
|
-
if (KDF.includes(
|
|
2512
|
-
if (jwk !== void 0) checkJWK(operation, jwk,
|
|
2513
|
-
const invalid2 = () => fail2(operation, `the ${format2} data is not a valid ${
|
|
2502
|
+
const wrong = usages.find((usage) => !USAGES[name2][type].includes(usage));
|
|
2503
|
+
if (wrong !== void 0) throw fail2(operation, `${wrong} is not a usage of a ${type} ${name2} key`);
|
|
2504
|
+
if (KDF.includes(name2) && extractable) throw fail2(operation, `${name2} keys cannot be extractable`);
|
|
2505
|
+
if (jwk !== void 0) checkJWK(operation, jwk, name2, type, hash, curve, extractable, usages);
|
|
2506
|
+
const invalid2 = () => fail2(operation, `the ${format2} data is not a valid ${name2} key`);
|
|
2514
2507
|
let material;
|
|
2515
2508
|
if (symmetric) {
|
|
2516
2509
|
const bytes2 = data ?? fromBase64url(jwk.k);
|
|
2517
2510
|
if (bytes2 === void 0) throw invalid2();
|
|
2518
|
-
if (AES_KEYS.includes(
|
|
2519
|
-
if (
|
|
2520
|
-
if (
|
|
2521
|
-
if (KDF.includes(
|
|
2522
|
-
throw fail2(operation, `${
|
|
2511
|
+
if (AES_KEYS.includes(name2) && ![16, 24, 32].includes(bytes2.length)) throw fail2(operation, `an AES key must be 128, 192 or 256 bits, not ${bytes2.length * 8}`);
|
|
2512
|
+
if (name2 === "HMAC" && bytes2.length === 0) throw invalid2();
|
|
2513
|
+
if (name2 === "HMAC" && bytes2.length > MAX_HMAC_BYTES) throw fail2(operation, `an HMAC key can be at most ${MAX_HMAC_BYTES * 8} bits, not ${bytes2.length * 8}`);
|
|
2514
|
+
if (KDF.includes(name2) && bytes2.length > MAX_DERIVE_BYTES) {
|
|
2515
|
+
throw fail2(operation, `${name2} key material can be at most ${MAX_DERIVE_BYTES * 8} bits, not ${bytes2.length * 8}`);
|
|
2523
2516
|
}
|
|
2524
2517
|
if (hmacLength !== void 0 && hmacLength !== bytes2.length * 8) {
|
|
2525
2518
|
throw fail2(operation, `HMAC length ${hmacLength} does not match the ${bytes2.length * 8}-bit key data`);
|
|
2526
2519
|
}
|
|
2527
2520
|
material = { kty: "oct", k: base64url(bytes2) };
|
|
2528
2521
|
} else {
|
|
2529
|
-
if (format2 === "raw" && ELLIPTIC.includes(
|
|
2530
|
-
if (format2 === "raw" && fixedCurve(
|
|
2531
|
-
const imported = await webImport(format2, data ?? materialOf(jwk),
|
|
2522
|
+
if (format2 === "raw" && ELLIPTIC.includes(name2) && (data[0] !== 4 || data.length !== 1 + 2 * COORDINATE_BYTES[curve])) throw invalid2();
|
|
2523
|
+
if (format2 === "raw" && fixedCurve(name2) !== void 0 && data.length !== 32) throw invalid2();
|
|
2524
|
+
const imported = await webImport(format2, data ?? materialOf(jwk), name2, hash, curve, type).catch(() => {
|
|
2532
2525
|
throw invalid2();
|
|
2533
2526
|
});
|
|
2534
2527
|
material = materialOf(await subtle().exportKey("jwk", imported));
|
|
2535
|
-
if (format2 === "jwk" && type === "private" && !RSA.includes(
|
|
2528
|
+
if (format2 === "jwk" && type === "private" && !RSA.includes(name2)) await checkPair(material, name2, curve).catch(() => {
|
|
2536
2529
|
throw invalid2();
|
|
2537
2530
|
});
|
|
2538
2531
|
}
|
|
2539
2532
|
if (usages.length === 0 && type !== "public") throw fail2(operation, `a ${type} key needs at least one usage`);
|
|
2540
|
-
return makeKey(type, extractable, keyAlgorithm(
|
|
2533
|
+
return makeKey(type, extractable, keyAlgorithm(name2, material, { hash, curve }), usages, material);
|
|
2541
2534
|
}
|
|
2542
|
-
function webImport(format2, keyData,
|
|
2543
|
-
const algorithm = RSA.includes(
|
|
2544
|
-
const usages = [...USAGES[
|
|
2535
|
+
function webImport(format2, keyData, name2, hash, curve, type) {
|
|
2536
|
+
const algorithm = RSA.includes(name2) ? { name: name2, hash } : ELLIPTIC.includes(name2) ? { name: name2, namedCurve: curve } : { name: name2 };
|
|
2537
|
+
const usages = [...USAGES[name2][type]];
|
|
2545
2538
|
return format2 === "jwk" ? subtle().importKey("jwk", { ...keyData, ext: true }, algorithm, true, usages) : subtle().importKey(format2, keyData, algorithm, true, usages);
|
|
2546
2539
|
}
|
|
2547
2540
|
async function checkPair(material, keyName, curve) {
|
|
@@ -2551,37 +2544,37 @@ async function checkPair(material, keyName, curve) {
|
|
|
2551
2544
|
if ((await subtle().exportKey("jwk", imported)).x !== material.x) throw new Error("not a pair");
|
|
2552
2545
|
return;
|
|
2553
2546
|
}
|
|
2554
|
-
const
|
|
2555
|
-
const algorithm =
|
|
2547
|
+
const name2 = keyName === "ECDH" ? "ECDSA" : keyName;
|
|
2548
|
+
const algorithm = name2 === "ECDSA" ? { name: name2, namedCurve: curve } : { name: name2 };
|
|
2556
2549
|
const signer = await subtle().importKey("jwk", { ...material, ext: true }, algorithm, false, ["sign"]);
|
|
2557
2550
|
const verifier = await subtle().importKey("jwk", { ...publicMaterial(material), ext: true }, algorithm, false, ["verify"]);
|
|
2558
|
-
const params =
|
|
2551
|
+
const params = name2 === "ECDSA" ? { name: name2, hash: "SHA-256" } : { name: name2 };
|
|
2559
2552
|
const probe = new Uint8Array([1]);
|
|
2560
2553
|
const signature = new Uint8Array(await subtle().sign(params, signer, probe));
|
|
2561
2554
|
if (!await subtle().verify(params, verifier, signature, probe)) throw new Error("not a pair");
|
|
2562
2555
|
}
|
|
2563
2556
|
var X25519_PKCS8_PREFIX = [48, 46, 2, 1, 0, 48, 5, 6, 3, 43, 101, 110, 4, 34, 4, 32];
|
|
2564
|
-
function checkJWK(operation, jwk,
|
|
2565
|
-
const kty = ktyOf(
|
|
2557
|
+
function checkJWK(operation, jwk, name2, type, hash, curve, extractable, usages) {
|
|
2558
|
+
const kty = ktyOf(name2);
|
|
2566
2559
|
if (jwk.kty !== kty) throw fail2(operation, `the JWK kty must be ${kty}`);
|
|
2567
|
-
const crv = ELLIPTIC.includes(
|
|
2560
|
+
const crv = ELLIPTIC.includes(name2) ? curve : fixedCurve(name2);
|
|
2568
2561
|
if (crv !== void 0 && jwk.crv !== crv) throw fail2(operation, `the JWK crv must be ${crv}`);
|
|
2569
|
-
if (jwk.alg !== void 0 && !AGREEMENT.includes(
|
|
2570
|
-
const bits = AES_KEYS.includes(
|
|
2571
|
-
const expected = jwkAlg(
|
|
2572
|
-
if (jwk.alg !== expected && !(
|
|
2562
|
+
if (jwk.alg !== void 0 && !AGREEMENT.includes(name2)) {
|
|
2563
|
+
const bits = AES_KEYS.includes(name2) ? (fromBase64url(jwk.k)?.length ?? 0) * 8 : void 0;
|
|
2564
|
+
const expected = jwkAlg(name2, hash, bits, curve);
|
|
2565
|
+
if (jwk.alg !== expected && !(name2 === "Ed25519" && jwk.alg === "EdDSA")) throw fail2(operation, `the JWK alg ${String(jwk.alg)} does not match ${expected}`);
|
|
2573
2566
|
}
|
|
2574
2567
|
if (jwk.use !== void 0 && usages.length > 0) {
|
|
2575
|
-
const use = ENCRYPTION.includes(
|
|
2568
|
+
const use = ENCRYPTION.includes(name2) || name2 === "AES-KW" || AGREEMENT.includes(name2) ? "enc" : "sig";
|
|
2576
2569
|
if (jwk.use !== use) throw fail2(operation, `the JWK use must be ${use}`);
|
|
2577
2570
|
}
|
|
2578
2571
|
if (jwk.key_ops !== void 0) {
|
|
2579
|
-
if (!Array.isArray(jwk.key_ops)) throw fail2(operation, `the jwk data is not a valid ${
|
|
2572
|
+
if (!Array.isArray(jwk.key_ops)) throw fail2(operation, `the jwk data is not a valid ${name2} key`);
|
|
2580
2573
|
const missing = usages.find((usage) => !jwk.key_ops.includes(usage));
|
|
2581
2574
|
if (missing !== void 0) throw fail2(operation, `the JWK key_ops do not include ${missing}`);
|
|
2582
2575
|
}
|
|
2583
2576
|
if (jwk.ext === false && extractable) throw fail2(operation, "the JWK is marked not extractable");
|
|
2584
|
-
if (type === "private" && RSA.includes(
|
|
2577
|
+
if (type === "private" && RSA.includes(name2) && PRIVATE_FIELDS.some((field) => jwk[field] === void 0)) {
|
|
2585
2578
|
throw fail2(operation, "the JWK has d but not all of p, q, dp, dq, qi");
|
|
2586
2579
|
}
|
|
2587
2580
|
}
|
|
@@ -2592,76 +2585,76 @@ async function exportKey(formatValue, keyValue) {
|
|
|
2592
2585
|
}
|
|
2593
2586
|
async function exported(operation, format2, key) {
|
|
2594
2587
|
if (!key.extractable) throw fail2(operation, "the key is not extractable");
|
|
2595
|
-
const
|
|
2596
|
-
const formats = key.type === "secret" ? ["raw", "jwk"] : key.type === "private" ? ["pkcs8", "jwk"] : RSA.includes(
|
|
2597
|
-
if (!formats.includes(format2)) throw fail2(operation, `a ${key.type} ${
|
|
2588
|
+
const name2 = key.algorithm.name;
|
|
2589
|
+
const formats = key.type === "secret" ? ["raw", "jwk"] : key.type === "private" ? ["pkcs8", "jwk"] : RSA.includes(name2) ? ["spki", "jwk"] : ["raw", "spki", "jwk"];
|
|
2590
|
+
if (!formats.includes(format2)) throw fail2(operation, `a ${key.type} ${name2} key cannot be exported as ${format2}`);
|
|
2598
2591
|
if (format2 === "jwk") {
|
|
2599
2592
|
const bits = key.algorithm.length;
|
|
2600
|
-
const alg = jwkAlg(
|
|
2593
|
+
const alg = jwkAlg(name2, key.algorithm.hash?.name, bits, void 0);
|
|
2601
2594
|
return { ...key.material, ...alg === void 0 ? {} : { alg }, ext: key.extractable, key_ops: [...key.usages] };
|
|
2602
2595
|
}
|
|
2603
2596
|
if (key.type === "secret") return fromBase64url(key.material.k);
|
|
2604
|
-
const web = await webImport("jwk", key.material,
|
|
2597
|
+
const web = await webImport("jwk", key.material, name2, key.algorithm.hash?.name, key.algorithm.namedCurve, key.type);
|
|
2605
2598
|
return new Uint8Array(await subtle().exportKey(format2, web));
|
|
2606
2599
|
}
|
|
2607
|
-
function signingParams(operation,
|
|
2608
|
-
if (
|
|
2609
|
-
if (
|
|
2600
|
+
function signingParams(operation, name2, params) {
|
|
2601
|
+
if (name2 === "RSA-PSS") return { saltLength: integerOf2(operation, params, "saltLength", name2) };
|
|
2602
|
+
if (name2 === "ECDSA") return { hash: hashOf(operation, params.hash, name2) };
|
|
2610
2603
|
return {};
|
|
2611
2604
|
}
|
|
2612
|
-
function signingKey(operation, key,
|
|
2613
|
-
checkKey(operation, key,
|
|
2614
|
-
requireType(operation, key,
|
|
2615
|
-
if (
|
|
2605
|
+
function signingKey(operation, key, name2, saltLength) {
|
|
2606
|
+
checkKey(operation, key, name2, operation);
|
|
2607
|
+
requireType(operation, key, name2 === "HMAC" ? "secret" : operation === "sign" ? "private" : "public");
|
|
2608
|
+
if (name2 === "RSA-PSS" && saltLength !== HASH_BYTES[hashOfKey(key)]) {
|
|
2616
2609
|
throw fail2(operation, `RSA-PSS saltLength must be ${HASH_BYTES[hashOfKey(key)]} for ${hashOfKey(key)}, not ${saltLength}`);
|
|
2617
2610
|
}
|
|
2618
2611
|
}
|
|
2619
|
-
function webSigning(
|
|
2620
|
-
return
|
|
2612
|
+
function webSigning(name2, extra) {
|
|
2613
|
+
return name2 === "RSA-PSS" ? { name: name2, saltLength: extra.saltLength } : name2 === "ECDSA" ? { name: name2, hash: extra.hash } : { name: name2 };
|
|
2621
2614
|
}
|
|
2622
2615
|
async function sign(algorithm, keyValue, dataValue) {
|
|
2623
2616
|
const operation = "sign";
|
|
2624
|
-
const { name, params } = algorithmOf(operation, algorithm);
|
|
2625
|
-
const extra = signingParams(operation,
|
|
2617
|
+
const { name: name2, params } = algorithmOf(operation, algorithm);
|
|
2618
|
+
const extra = signingParams(operation, name2, params);
|
|
2626
2619
|
const key = await keyOf(operation, keyValue);
|
|
2627
2620
|
const data = bytesArgument(operation, dataValue, "data");
|
|
2628
|
-
signingKey(operation, key,
|
|
2629
|
-
return new Uint8Array(await subtle().sign(webSigning(
|
|
2621
|
+
signingKey(operation, key, name2, extra.saltLength);
|
|
2622
|
+
return new Uint8Array(await subtle().sign(webSigning(name2, extra), await webKey(key, "sign"), data));
|
|
2630
2623
|
}
|
|
2631
2624
|
async function verify(algorithm, keyValue, signatureValue, dataValue) {
|
|
2632
2625
|
const operation = "verify";
|
|
2633
|
-
const { name, params } = algorithmOf(operation, algorithm);
|
|
2634
|
-
const extra = signingParams(operation,
|
|
2626
|
+
const { name: name2, params } = algorithmOf(operation, algorithm);
|
|
2627
|
+
const extra = signingParams(operation, name2, params);
|
|
2635
2628
|
const key = await keyOf(operation, keyValue);
|
|
2636
2629
|
const signature = bytesArgument(operation, signatureValue, "signature");
|
|
2637
2630
|
const data = bytesArgument(operation, dataValue, "data");
|
|
2638
|
-
signingKey(operation, key,
|
|
2639
|
-
return subtle().verify(webSigning(
|
|
2631
|
+
signingKey(operation, key, name2, extra.saltLength);
|
|
2632
|
+
return subtle().verify(webSigning(name2, extra), await webKey(key, "verify"), signature, data);
|
|
2640
2633
|
}
|
|
2641
|
-
function cipherParams(operation,
|
|
2642
|
-
switch (
|
|
2634
|
+
function cipherParams(operation, name2, params) {
|
|
2635
|
+
switch (name2) {
|
|
2643
2636
|
case "RSA-OAEP":
|
|
2644
|
-
return { label: optionalBytesParam(operation, params, "label",
|
|
2637
|
+
return { label: optionalBytesParam(operation, params, "label", name2) };
|
|
2645
2638
|
case "AES-CBC":
|
|
2646
|
-
return { iv: bytesParam(operation, params, "iv",
|
|
2639
|
+
return { iv: bytesParam(operation, params, "iv", name2) };
|
|
2647
2640
|
case "AES-CTR":
|
|
2648
|
-
return { counter: bytesParam(operation, params, "counter",
|
|
2641
|
+
return { counter: bytesParam(operation, params, "counter", name2), length: integerOf2(operation, params, "length", name2) };
|
|
2649
2642
|
default:
|
|
2650
2643
|
return {
|
|
2651
|
-
iv: bytesParam(operation, params, "iv",
|
|
2652
|
-
additionalData: optionalBytesParam(operation, params, "additionalData",
|
|
2653
|
-
tagLength: params.tagLength === void 0 ? 128 : integerOf2(operation, params, "tagLength",
|
|
2644
|
+
iv: bytesParam(operation, params, "iv", name2),
|
|
2645
|
+
additionalData: optionalBytesParam(operation, params, "additionalData", name2),
|
|
2646
|
+
tagLength: params.tagLength === void 0 ? 128 : integerOf2(operation, params, "tagLength", name2)
|
|
2654
2647
|
};
|
|
2655
2648
|
}
|
|
2656
2649
|
}
|
|
2657
|
-
function checkCipher(operation,
|
|
2658
|
-
if (
|
|
2650
|
+
function checkCipher(operation, name2, cipher, data, key) {
|
|
2651
|
+
if (name2 === "RSA-OAEP") {
|
|
2659
2652
|
if (cipher.label !== void 0 && cipher.label.length > 0) throw fail2(operation, "RSA-OAEP does not support a label");
|
|
2660
2653
|
const max = Math.ceil(bitLength(fromBase64url(key.material.n)) / 8) - 2 * HASH_BYTES[hashOfKey(key)] - 2;
|
|
2661
2654
|
if ((operation === "encrypt" || operation === "wrapKey") && data.length > max) throw fail2(operation, `the data is longer than ${max} bytes, the most this RSA-OAEP key can encrypt`);
|
|
2662
|
-
} else if (
|
|
2655
|
+
} else if (name2 === "AES-CBC") {
|
|
2663
2656
|
if (cipher.iv.length !== 16) throw fail2(operation, `AES-CBC iv must be 16 bytes, not ${cipher.iv.length}`);
|
|
2664
|
-
} else if (
|
|
2657
|
+
} else if (name2 === "AES-CTR") {
|
|
2665
2658
|
if (cipher.counter.length !== 16) throw fail2(operation, `AES-CTR counter must be 16 bytes, not ${cipher.counter.length}`);
|
|
2666
2659
|
if (cipher.length < 1 || cipher.length > 128) throw fail2(operation, `AES-CTR length must be from 1 to 128, not ${cipher.length}`);
|
|
2667
2660
|
const blocks = Math.ceil(data.length / 16);
|
|
@@ -2673,35 +2666,35 @@ function checkCipher(operation, name, cipher, data, key) {
|
|
|
2673
2666
|
if (!GCM_TAG_LENGTHS.includes(cipher.tagLength)) throw fail2(operation, `AES-GCM tagLength must be 32, 64, 96, 104, 112, 120 or 128, not ${cipher.tagLength}`);
|
|
2674
2667
|
}
|
|
2675
2668
|
}
|
|
2676
|
-
function webCipher(
|
|
2677
|
-
switch (
|
|
2669
|
+
function webCipher(name2, cipher) {
|
|
2670
|
+
switch (name2) {
|
|
2678
2671
|
case "RSA-OAEP":
|
|
2679
|
-
return { name };
|
|
2672
|
+
return { name: name2 };
|
|
2680
2673
|
case "AES-CBC":
|
|
2681
|
-
return { name, iv: cipher.iv };
|
|
2674
|
+
return { name: name2, iv: cipher.iv };
|
|
2682
2675
|
case "AES-CTR":
|
|
2683
|
-
return { name, counter: cipher.counter, length: cipher.length };
|
|
2676
|
+
return { name: name2, counter: cipher.counter, length: cipher.length };
|
|
2684
2677
|
default:
|
|
2685
|
-
return { name, iv: cipher.iv, tagLength: cipher.tagLength, ...cipher.additionalData === void 0 ? {} : { additionalData: cipher.additionalData } };
|
|
2678
|
+
return { name: name2, iv: cipher.iv, tagLength: cipher.tagLength, ...cipher.additionalData === void 0 ? {} : { additionalData: cipher.additionalData } };
|
|
2686
2679
|
}
|
|
2687
2680
|
}
|
|
2688
2681
|
async function crypt(operation, algorithm, keyValue, dataValue) {
|
|
2689
|
-
const { name, params } = algorithmOf(operation, algorithm);
|
|
2690
|
-
const cipher = cipherParams(operation,
|
|
2682
|
+
const { name: name2, params } = algorithmOf(operation, algorithm);
|
|
2683
|
+
const cipher = cipherParams(operation, name2, params);
|
|
2691
2684
|
const key = await keyOf(operation, keyValue);
|
|
2692
2685
|
const data = bytesArgument(operation, dataValue, "data");
|
|
2693
|
-
checkKey(operation, key,
|
|
2694
|
-
requireType(operation, key,
|
|
2695
|
-
checkCipher(operation,
|
|
2686
|
+
checkKey(operation, key, name2, operation);
|
|
2687
|
+
requireType(operation, key, name2 === "RSA-OAEP" ? operation === "encrypt" ? "public" : "private" : "secret");
|
|
2688
|
+
checkCipher(operation, name2, cipher, data, key);
|
|
2696
2689
|
const web = await webKey(key, operation);
|
|
2697
2690
|
try {
|
|
2698
|
-
return new Uint8Array(await (operation === "encrypt" ? subtle().encrypt(webCipher(
|
|
2691
|
+
return new Uint8Array(await (operation === "encrypt" ? subtle().encrypt(webCipher(name2, cipher), web, data) : subtle().decrypt(webCipher(name2, cipher), web, data)));
|
|
2699
2692
|
} catch (error) {
|
|
2700
2693
|
if (operation === "encrypt") throw error;
|
|
2701
|
-
throw decryptionFailed(operation,
|
|
2694
|
+
throw decryptionFailed(operation, name2);
|
|
2702
2695
|
}
|
|
2703
2696
|
}
|
|
2704
|
-
var decryptionFailed = (operation,
|
|
2697
|
+
var decryptionFailed = (operation, name2) => fail2(operation, name2 === "AES-GCM" ? "AES-GCM tag check failed" : name2 === "AES-CBC" ? "AES-CBC decryption failed: the data or its padding is wrong" : name2 === "AES-KW" ? "AES-KW integrity check failed" : `${name2} decryption failed`);
|
|
2705
2698
|
async function digest(algorithm, dataValue) {
|
|
2706
2699
|
const operation = "digest";
|
|
2707
2700
|
const given = typeof algorithm === "string" ? algorithm : isObject2(algorithm) && typeof algorithm.name === "string" ? algorithm.name : void 0;
|
|
@@ -2710,15 +2703,15 @@ async function digest(algorithm, dataValue) {
|
|
|
2710
2703
|
return new Uint8Array(await subtle().digest(hash, bytesArgument(operation, dataValue, "data")));
|
|
2711
2704
|
}
|
|
2712
2705
|
async function derivationOf(operation, algorithm) {
|
|
2713
|
-
const { name, params } = algorithmOf(operation, algorithm);
|
|
2714
|
-
if (AGREEMENT.includes(
|
|
2715
|
-
if (params.public === void 0) throw fail2(operation, `${
|
|
2716
|
-
return { name, publicKey: await keyOf(operation, params.public, "public") };
|
|
2706
|
+
const { name: name2, params } = algorithmOf(operation, algorithm);
|
|
2707
|
+
if (AGREEMENT.includes(name2)) {
|
|
2708
|
+
if (params.public === void 0) throw fail2(operation, `${name2} needs public`);
|
|
2709
|
+
return { name: name2, publicKey: await keyOf(operation, params.public, "public") };
|
|
2717
2710
|
}
|
|
2718
|
-
const hash = hashOf(operation, params.hash,
|
|
2719
|
-
const salt = boundedBytes(operation, params, "salt",
|
|
2720
|
-
if (
|
|
2721
|
-
return { name, hash, salt, iterations: integerOf2(operation, params, "iterations",
|
|
2711
|
+
const hash = hashOf(operation, params.hash, name2);
|
|
2712
|
+
const salt = boundedBytes(operation, params, "salt", name2);
|
|
2713
|
+
if (name2 === "HKDF") return { name: name2, hash, salt, info: boundedBytes(operation, params, "info", name2) };
|
|
2714
|
+
return { name: name2, hash, salt, iterations: integerOf2(operation, params, "iterations", name2) };
|
|
2722
2715
|
}
|
|
2723
2716
|
function boundedBytes(operation, params, field, owner) {
|
|
2724
2717
|
const bytes2 = bytesParam(operation, params, field, owner);
|
|
@@ -2730,16 +2723,16 @@ function lengthOf(operation, value) {
|
|
|
2730
2723
|
if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value >= 1e15) throw fail2(operation, "length must be a whole number of bits or null");
|
|
2731
2724
|
return value;
|
|
2732
2725
|
}
|
|
2733
|
-
var article = (
|
|
2726
|
+
var article = (name2) => /^[AEIOX]/.test(name2) ? "an" : "a";
|
|
2734
2727
|
async function derive(operation, derivation, key, length, usage) {
|
|
2735
|
-
const { name } = derivation;
|
|
2736
|
-
checkKey(operation, key,
|
|
2737
|
-
if (AGREEMENT.includes(
|
|
2738
|
-
if (length === null) throw fail2(operation, `${
|
|
2739
|
-
if (length % 8 !== 0) throw fail2(operation, `${
|
|
2740
|
-
if (length > MAX_DERIVE_BYTES * 8) throw fail2(operation, `${
|
|
2728
|
+
const { name: name2 } = derivation;
|
|
2729
|
+
checkKey(operation, key, name2, usage);
|
|
2730
|
+
if (AGREEMENT.includes(name2)) return agree(operation, derivation, key, length);
|
|
2731
|
+
if (length === null) throw fail2(operation, `${name2} needs length`);
|
|
2732
|
+
if (length % 8 !== 0) throw fail2(operation, `${name2} length must be a multiple of 8, not ${length}`);
|
|
2733
|
+
if (length > MAX_DERIVE_BYTES * 8) throw fail2(operation, `${name2} can derive at most ${MAX_DERIVE_BYTES * 8} bits, not ${length}`);
|
|
2741
2734
|
const iterations = derivation.iterations ?? 0;
|
|
2742
|
-
if (
|
|
2735
|
+
if (name2 === "PBKDF2") {
|
|
2743
2736
|
if (iterations < 1) throw fail2(operation, `PBKDF2 iterations must be at least 1, not ${iterations}`);
|
|
2744
2737
|
const work = iterations * Math.ceil(length / (HASH_BYTES[derivation.hash] * 8));
|
|
2745
2738
|
if (work > MAX_PBKDF2_WORK) {
|
|
@@ -2747,29 +2740,29 @@ async function derive(operation, derivation, key, length, usage) {
|
|
|
2747
2740
|
}
|
|
2748
2741
|
}
|
|
2749
2742
|
if (length === 0) return new Uint8Array(0);
|
|
2750
|
-
const params =
|
|
2743
|
+
const params = name2 === "HKDF" ? { name: name2, hash: derivation.hash, salt: derivation.salt, info: derivation.info } : { name: name2, hash: derivation.hash, salt: derivation.salt, iterations };
|
|
2751
2744
|
return new Uint8Array(await subtle().deriveBits(params, await webKey(key, "deriveBits"), length));
|
|
2752
2745
|
}
|
|
2753
2746
|
async function agree(operation, derivation, key, length) {
|
|
2754
|
-
const { name } = derivation;
|
|
2747
|
+
const { name: name2 } = derivation;
|
|
2755
2748
|
const other = derivation.publicKey;
|
|
2756
2749
|
requireType(operation, key, "private");
|
|
2757
2750
|
if (other.type !== "public") throw fail2(operation, "public must be a public key");
|
|
2758
|
-
if (other.algorithm.name !==
|
|
2751
|
+
if (other.algorithm.name !== name2) throw fail2(operation, `the public key is ${article(other.algorithm.name)} ${other.algorithm.name} key, not ${name2}`);
|
|
2759
2752
|
const curve = key.algorithm.namedCurve;
|
|
2760
2753
|
if (curve !== void 0 && other.algorithm.namedCurve !== curve) throw fail2(operation, `the public key is on ${other.algorithm.namedCurve}, not ${curve}`);
|
|
2761
2754
|
const full = curve === void 0 ? 256 : COORDINATE_BYTES[curve] * 8;
|
|
2762
2755
|
if (length !== null && length > full) {
|
|
2763
|
-
throw fail2(operation, curve === void 0 ? `${
|
|
2756
|
+
throw fail2(operation, curve === void 0 ? `${name2} can derive at most ${full} bits, not ${length}` : `${name2} can derive at most ${full} bits on ${curve}, not ${length}`);
|
|
2764
2757
|
}
|
|
2765
2758
|
const smallOrder = () => fail2(operation, "the X25519 shared secret is all zero: the public key is a small-order point");
|
|
2766
2759
|
let secret;
|
|
2767
2760
|
try {
|
|
2768
|
-
secret = new Uint8Array(await subtle().deriveBits({ name, public: await webKey(other, void 0) }, await webKey(key, "deriveBits"), null));
|
|
2761
|
+
secret = new Uint8Array(await subtle().deriveBits({ name: name2, public: await webKey(other, void 0) }, await webKey(key, "deriveBits"), null));
|
|
2769
2762
|
} catch {
|
|
2770
|
-
throw
|
|
2763
|
+
throw name2 === "X25519" ? smallOrder() : fail2(operation, `${name2} could not derive bits with this key`);
|
|
2771
2764
|
}
|
|
2772
|
-
if (
|
|
2765
|
+
if (name2 === "X25519" && secret.every((byte) => byte === 0)) throw smallOrder();
|
|
2773
2766
|
if (length === null) return secret;
|
|
2774
2767
|
const bits = secret.slice(0, Math.ceil(length / 8));
|
|
2775
2768
|
if (length % 8 !== 0) bits[bits.length - 1] &= 255 << 8 - length % 8 & 255;
|
|
@@ -2781,28 +2774,28 @@ async function deriveBits(algorithm, baseKey, lengthValue) {
|
|
|
2781
2774
|
const key = await keyOf(operation, baseKey);
|
|
2782
2775
|
return derive(operation, derivation, key, lengthOf(operation, lengthValue), "deriveBits");
|
|
2783
2776
|
}
|
|
2784
|
-
function derivedLength(operation,
|
|
2785
|
-
if (AES_KEYS.includes(
|
|
2786
|
-
const length = integerOf2(operation, params, "length",
|
|
2777
|
+
function derivedLength(operation, name2, params) {
|
|
2778
|
+
if (AES_KEYS.includes(name2)) {
|
|
2779
|
+
const length = integerOf2(operation, params, "length", name2);
|
|
2787
2780
|
if (![128, 192, 256].includes(length)) throw fail2(operation, `an AES key must be 128, 192 or 256 bits, not ${length}`);
|
|
2788
2781
|
return length;
|
|
2789
2782
|
}
|
|
2790
|
-
if (
|
|
2791
|
-
const hash = hashOf(operation, params.hash,
|
|
2792
|
-
const length = params.length === void 0 ? HASH_BLOCK_BITS[hash] : integerOf2(operation, params, "length",
|
|
2783
|
+
if (name2 === "HMAC") {
|
|
2784
|
+
const hash = hashOf(operation, params.hash, name2);
|
|
2785
|
+
const length = params.length === void 0 ? HASH_BLOCK_BITS[hash] : integerOf2(operation, params, "length", name2);
|
|
2793
2786
|
if (length <= 0 || length % 8 !== 0) throw fail2(operation, `HMAC length must be a positive multiple of 8, not ${length}`);
|
|
2794
2787
|
if (length > MAX_HMAC_BYTES * 8) throw fail2(operation, `an HMAC key can be at most ${MAX_HMAC_BYTES * 8} bits, not ${length}`);
|
|
2795
2788
|
return length;
|
|
2796
2789
|
}
|
|
2797
|
-
if (KDF.includes(
|
|
2798
|
-
throw fail2(operation, `${
|
|
2790
|
+
if (KDF.includes(name2)) return null;
|
|
2791
|
+
throw fail2(operation, `${name2} keys cannot be derived`);
|
|
2799
2792
|
}
|
|
2800
2793
|
async function deriveKey(algorithm, baseKey, derivedKeyType, extractableValue, usagesValue) {
|
|
2801
2794
|
const operation = "deriveKey";
|
|
2802
2795
|
const derivation = await derivationOf(operation, algorithm);
|
|
2803
2796
|
const key = await keyOf(operation, baseKey);
|
|
2804
|
-
const { name, params } = algorithmOf(operation, derivedKeyType, "importKey");
|
|
2805
|
-
const length = derivedLength(operation,
|
|
2797
|
+
const { name: name2, params } = algorithmOf(operation, derivedKeyType, "importKey");
|
|
2798
|
+
const length = derivedLength(operation, name2, params);
|
|
2806
2799
|
extractableOf(operation, extractableValue);
|
|
2807
2800
|
usagesOf(operation, usagesValue);
|
|
2808
2801
|
const bits = await derive(operation, derivation, key, length, "deriveKey");
|
|
@@ -2814,8 +2807,8 @@ function jwkBytes(jwk, pad) {
|
|
|
2814
2807
|
return new TextEncoder().encode(text);
|
|
2815
2808
|
}
|
|
2816
2809
|
function wrapping(operation, algorithm) {
|
|
2817
|
-
const { name, params } = algorithmOf(operation, algorithm);
|
|
2818
|
-
return { name, cipher:
|
|
2810
|
+
const { name: name2, params } = algorithmOf(operation, algorithm);
|
|
2811
|
+
return { name: name2, cipher: name2 === "AES-KW" ? {} : cipherParams(operation, name2, params) };
|
|
2819
2812
|
}
|
|
2820
2813
|
function checkKeyWrap(operation, data) {
|
|
2821
2814
|
const least = operation === "wrapKey" ? 16 : 24;
|
|
@@ -2827,24 +2820,24 @@ var HMAC_CARRIER = { name: "HMAC", hash: "SHA-256" };
|
|
|
2827
2820
|
async function wrapKey(formatValue, keyValue, wrappingKeyValue, algorithm) {
|
|
2828
2821
|
const operation = "wrapKey";
|
|
2829
2822
|
const format2 = formatOf(operation, formatValue);
|
|
2830
|
-
const { name, cipher } = wrapping(operation, algorithm);
|
|
2823
|
+
const { name: name2, cipher } = wrapping(operation, algorithm);
|
|
2831
2824
|
const key = await keyOf(operation, keyValue);
|
|
2832
2825
|
const wrappingKey = await keyOf(operation, wrappingKeyValue);
|
|
2833
|
-
checkKey(operation, wrappingKey,
|
|
2834
|
-
requireType(operation, wrappingKey,
|
|
2826
|
+
checkKey(operation, wrappingKey, name2, "wrapKey");
|
|
2827
|
+
requireType(operation, wrappingKey, name2 === "RSA-OAEP" ? "public" : "secret");
|
|
2835
2828
|
const output = await exported(operation, format2, key);
|
|
2836
|
-
const data = output instanceof Uint8Array ? output : jwkBytes(output,
|
|
2837
|
-
if (
|
|
2829
|
+
const data = output instanceof Uint8Array ? output : jwkBytes(output, name2 === "AES-KW");
|
|
2830
|
+
if (name2 === "AES-KW") {
|
|
2838
2831
|
checkKeyWrap(operation, data);
|
|
2839
2832
|
} else {
|
|
2840
|
-
checkCipher(operation,
|
|
2833
|
+
checkCipher(operation, name2, cipher, data, wrappingKey);
|
|
2841
2834
|
}
|
|
2842
2835
|
try {
|
|
2843
|
-
if (
|
|
2836
|
+
if (name2 !== "AES-KW") return new Uint8Array(await subtle().encrypt(webCipher(name2, cipher), await webKey(wrappingKey, "encrypt"), data));
|
|
2844
2837
|
const carrier = await subtle().importKey("raw", data, HMAC_CARRIER, true, ["sign"]);
|
|
2845
|
-
return new Uint8Array(await subtle().wrapKey("raw", carrier, await webKey(wrappingKey, "wrapKey"), { name }));
|
|
2838
|
+
return new Uint8Array(await subtle().wrapKey("raw", carrier, await webKey(wrappingKey, "wrapKey"), { name: name2 }));
|
|
2846
2839
|
} catch {
|
|
2847
|
-
throw fail2(operation, `${
|
|
2840
|
+
throw fail2(operation, `${name2} could not wrap with this key`);
|
|
2848
2841
|
}
|
|
2849
2842
|
}
|
|
2850
2843
|
function jwkOf(operation, data) {
|
|
@@ -2863,25 +2856,25 @@ async function unwrapKey(formatValue, wrappedValue, unwrappingKeyValue, algorith
|
|
|
2863
2856
|
const format2 = formatOf(operation, formatValue);
|
|
2864
2857
|
const wrapped2 = bytesArgument(operation, wrappedValue, "wrappedKey");
|
|
2865
2858
|
if (wrapped2.length > MAX_WRAPPED_BYTES) throw fail2(operation, `wrappedKey can be at most ${MAX_WRAPPED_BYTES} bytes, not ${wrapped2.length}`);
|
|
2866
|
-
const { name, cipher } = wrapping(operation, algorithm);
|
|
2859
|
+
const { name: name2, cipher } = wrapping(operation, algorithm);
|
|
2867
2860
|
const unwrappingKey = await keyOf(operation, unwrappingKeyValue);
|
|
2868
2861
|
algorithmOf(operation, keyAlgorithm2, "importKey");
|
|
2869
2862
|
extractableOf(operation, extractableValue);
|
|
2870
2863
|
usagesOf(operation, usagesValue);
|
|
2871
|
-
checkKey(operation, unwrappingKey,
|
|
2872
|
-
requireType(operation, unwrappingKey,
|
|
2873
|
-
if (
|
|
2874
|
-
else checkCipher(operation,
|
|
2864
|
+
checkKey(operation, unwrappingKey, name2, "unwrapKey");
|
|
2865
|
+
requireType(operation, unwrappingKey, name2 === "RSA-OAEP" ? "private" : "secret");
|
|
2866
|
+
if (name2 === "AES-KW") checkKeyWrap(operation, wrapped2);
|
|
2867
|
+
else checkCipher(operation, name2, cipher, wrapped2, unwrappingKey);
|
|
2875
2868
|
let data;
|
|
2876
2869
|
try {
|
|
2877
|
-
if (
|
|
2878
|
-
const carrier = await subtle().unwrapKey("raw", wrapped2, await webKey(unwrappingKey, "unwrapKey"), { name }, HMAC_CARRIER, true, ["sign"]);
|
|
2870
|
+
if (name2 === "AES-KW") {
|
|
2871
|
+
const carrier = await subtle().unwrapKey("raw", wrapped2, await webKey(unwrappingKey, "unwrapKey"), { name: name2 }, HMAC_CARRIER, true, ["sign"]);
|
|
2879
2872
|
data = new Uint8Array(await subtle().exportKey("raw", carrier));
|
|
2880
2873
|
} else {
|
|
2881
|
-
data = new Uint8Array(await subtle().decrypt(webCipher(
|
|
2874
|
+
data = new Uint8Array(await subtle().decrypt(webCipher(name2, cipher), await webKey(unwrappingKey, "decrypt"), wrapped2));
|
|
2882
2875
|
}
|
|
2883
2876
|
} catch {
|
|
2884
|
-
throw decryptionFailed(operation,
|
|
2877
|
+
throw decryptionFailed(operation, name2);
|
|
2885
2878
|
}
|
|
2886
2879
|
return importKeyAs(operation, format2, format2 === "jwk" ? jwkOf(operation, data) : data, keyAlgorithm2, extractableValue, usagesValue);
|
|
2887
2880
|
}
|
|
@@ -2902,15 +2895,15 @@ function createSubtle() {
|
|
|
2902
2895
|
};
|
|
2903
2896
|
}
|
|
2904
2897
|
|
|
2905
|
-
//
|
|
2898
|
+
// host/krillplayer.ts
|
|
2906
2899
|
function userAddressesOf(manifest, parameters) {
|
|
2907
|
-
return (manifest.parameters ?? []).flatMap(({ name, kind }) => kind === "url" && parameters[
|
|
2900
|
+
return (manifest.parameters ?? []).flatMap(({ name: name2, kind }) => kind === "url" && parameters[name2] !== void 0 ? [parameters[name2]] : []);
|
|
2908
2901
|
}
|
|
2909
2902
|
function userHostsOf(manifest, parameters) {
|
|
2910
|
-
return (manifest.parameters ?? []).flatMap(({ name, kind }) => {
|
|
2911
|
-
if (kind !== "url" || parameters[
|
|
2903
|
+
return (manifest.parameters ?? []).flatMap(({ name: name2, kind }) => {
|
|
2904
|
+
if (kind !== "url" || parameters[name2] === void 0) return [];
|
|
2912
2905
|
try {
|
|
2913
|
-
const host = normalForm(parameters[
|
|
2906
|
+
const host = normalForm(parameters[name2])?.host;
|
|
2914
2907
|
return host === void 0 ? [] : [host];
|
|
2915
2908
|
} catch {
|
|
2916
2909
|
return [];
|
|
@@ -2990,8 +2983,8 @@ function createGuides(now2 = Date.now) {
|
|
|
2990
2983
|
scope({ pluginId, sourceId }) {
|
|
2991
2984
|
const prefix = JSON.stringify([pluginId, sourceId]);
|
|
2992
2985
|
return async (source, load) => {
|
|
2993
|
-
const
|
|
2994
|
-
const key = prefix + JSON.stringify([source.url,
|
|
2986
|
+
const headers2 = Object.entries(source.headers ?? {}).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
|
|
2987
|
+
const key = prefix + JSON.stringify([source.url, headers2]);
|
|
2995
2988
|
const entry = entries.get(key);
|
|
2996
2989
|
if (entry !== void 0 && entry.expiresAt > now2()) return entry.guide;
|
|
2997
2990
|
const pending = loading.get(key) ?? fill2(key, source.maxAge ?? GUIDE_MAX_AGE_SECONDS, load);
|
|
@@ -3081,10 +3074,10 @@ function xmltvQuery(value) {
|
|
|
3081
3074
|
}
|
|
3082
3075
|
return query;
|
|
3083
3076
|
}
|
|
3084
|
-
async function loadGuide(fetch, network, grants, { url, headers }) {
|
|
3077
|
+
async function loadGuide(fetch, network, grants, { url, headers: headers2 }) {
|
|
3085
3078
|
const { response } = await send(
|
|
3086
3079
|
fetch,
|
|
3087
|
-
{ url, headers },
|
|
3080
|
+
{ url, headers: headers2 },
|
|
3088
3081
|
"guide",
|
|
3089
3082
|
grants,
|
|
3090
3083
|
network.lookup,
|
|
@@ -3112,16 +3105,16 @@ function createStorage() {
|
|
|
3112
3105
|
return {
|
|
3113
3106
|
get: (key) => entries().get(String(key)) ?? null,
|
|
3114
3107
|
set(key, value) {
|
|
3115
|
-
const
|
|
3108
|
+
const name2 = String(key);
|
|
3116
3109
|
if (typeof value !== "string") throw new TypeError("krillplayer.storage only stores strings");
|
|
3117
|
-
if (utf8Length(
|
|
3110
|
+
if (utf8Length(name2) > STORAGE_LIMITS.keyBytes) throw new RangeError(`krillplayer.storage keys are at most ${STORAGE_LIMITS.keyBytes} bytes`);
|
|
3118
3111
|
if (utf8Length(value) > STORAGE_LIMITS.valueBytes) throw new RangeError(`krillplayer.storage values are at most ${STORAGE_LIMITS.valueBytes} bytes`);
|
|
3119
|
-
const previous = entries().get(
|
|
3120
|
-
const replaced = previous === void 0 ? 0 : utf8Length(
|
|
3121
|
-
if (used() - replaced + utf8Length(
|
|
3112
|
+
const previous = entries().get(name2);
|
|
3113
|
+
const replaced = previous === void 0 ? 0 : utf8Length(name2) + utf8Length(previous);
|
|
3114
|
+
if (used() - replaced + utf8Length(name2) + utf8Length(value) > STORAGE_LIMITS.pluginBytes) {
|
|
3122
3115
|
throw new RangeError(`krillplayer.storage is full: each plugin stores at most ${STORAGE_LIMITS.pluginBytes} bytes`);
|
|
3123
3116
|
}
|
|
3124
|
-
entries().set(
|
|
3117
|
+
entries().set(name2, value);
|
|
3125
3118
|
},
|
|
3126
3119
|
delete(key) {
|
|
3127
3120
|
entries().delete(String(key));
|
|
@@ -3153,7 +3146,7 @@ function createKrillPlayer({
|
|
|
3153
3146
|
const withheld = () => [
|
|
3154
3147
|
...credentialValues(current),
|
|
3155
3148
|
...handedKeys,
|
|
3156
|
-
...secrets.flatMap((
|
|
3149
|
+
...secrets.flatMap((name2) => parameters !== null && Object.hasOwn(parameters, name2) && parameters[name2] !== "" ? [parameters[name2]] : [])
|
|
3157
3150
|
];
|
|
3158
3151
|
const grants = () => ({
|
|
3159
3152
|
declared: network.hosts,
|
|
@@ -3217,8 +3210,8 @@ function createKrillPlayer({
|
|
|
3217
3210
|
},
|
|
3218
3211
|
parameters: { get: () => parameters === null ? null : { ...parameters } },
|
|
3219
3212
|
appKeys: {
|
|
3220
|
-
async get(
|
|
3221
|
-
const key = appKeyFor(appKeys,
|
|
3213
|
+
async get(name2) {
|
|
3214
|
+
const key = appKeyFor(appKeys, name2);
|
|
3222
3215
|
if (key !== null) handedKeys.add(key);
|
|
3223
3216
|
return key;
|
|
3224
3217
|
}
|
|
@@ -3231,31 +3224,31 @@ function createKrillPlayer({
|
|
|
3231
3224
|
error: pluginError
|
|
3232
3225
|
};
|
|
3233
3226
|
}
|
|
3234
|
-
function appKeyFor(appKeys,
|
|
3235
|
-
if (typeof
|
|
3236
|
-
if (appKeys === null || !appKeys.declared.includes(
|
|
3237
|
-
const key = appKeys.keys[
|
|
3227
|
+
function appKeyFor(appKeys, name2) {
|
|
3228
|
+
if (typeof name2 !== "string" || name2 === "") throw new TypeError("krillplayer.appKeys.get takes a non-empty name");
|
|
3229
|
+
if (appKeys === null || !appKeys.declared.includes(name2) || !Object.hasOwn(appKeys.keys, name2)) return null;
|
|
3230
|
+
const key = appKeys.keys[name2];
|
|
3238
3231
|
return typeof key === "string" && key !== "" ? key : null;
|
|
3239
3232
|
}
|
|
3240
3233
|
function toBytes(data) {
|
|
3241
3234
|
return typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data);
|
|
3242
3235
|
}
|
|
3243
3236
|
function responseHeaders(response, url) {
|
|
3244
|
-
const
|
|
3245
|
-
delete
|
|
3237
|
+
const headers2 = Object.fromEntries(response.headers);
|
|
3238
|
+
delete headers2["set-cookie"];
|
|
3246
3239
|
const host = new URL(url).hostname.toLowerCase();
|
|
3247
3240
|
const cookies = response.headers.getSetCookie().filter((line) => {
|
|
3248
3241
|
const attribute = line.split(";").slice(1).map((part) => part.trim()).find((part) => part.toLowerCase().startsWith("domain="));
|
|
3249
3242
|
const domain = attribute?.slice("domain=".length).replace(/^\.+/, "").toLowerCase();
|
|
3250
3243
|
return domain === void 0 || host === domain || host.endsWith(`.${domain}`);
|
|
3251
3244
|
});
|
|
3252
|
-
if (cookies.length > 0)
|
|
3253
|
-
return
|
|
3245
|
+
if (cookies.length > 0) headers2["set-cookie"] = cookies.join("\n");
|
|
3246
|
+
return headers2;
|
|
3254
3247
|
}
|
|
3255
|
-
async function send(fetch, { url, method = "GET", headers = {}, body }, use, grants, lookup2, limit = HTTP_LIMITS.responseBytes, tooLarge = `krillplayer.http: the response is larger than ${limit} bytes`) {
|
|
3248
|
+
async function send(fetch, { url, method = "GET", headers: headers2 = {}, body }, use, grants, lookup2, limit = HTTP_LIMITS.responseBytes, tooLarge = `krillplayer.http: the response is larger than ${limit} bytes`) {
|
|
3256
3249
|
const bytes2 = body === void 0 ? void 0 : toBytes(body);
|
|
3257
3250
|
const chain = new Chain(use, grants);
|
|
3258
|
-
let pass = chain.first({ url, method, headers, body: bytes2 !== void 0 });
|
|
3251
|
+
let pass = chain.first({ url, method, headers: headers2, body: bytes2 !== void 0 });
|
|
3259
3252
|
let target = url;
|
|
3260
3253
|
for (; ; ) {
|
|
3261
3254
|
const looked = pass.publicOnly === null ? void 0 : lookup2?.(pass.address.host);
|
|
@@ -3334,12 +3327,12 @@ async function decompress(format2, data, limit = FORMAT_LIMITS.decompressedBytes
|
|
|
3334
3327
|
return output;
|
|
3335
3328
|
}
|
|
3336
3329
|
async function digest2(algorithm, data) {
|
|
3337
|
-
const
|
|
3338
|
-
if (
|
|
3339
|
-
return new Uint8Array(await crypto.subtle.digest(
|
|
3330
|
+
const name2 = DIGESTS.get(algorithm.toLowerCase());
|
|
3331
|
+
if (name2 === void 0) throw new TypeError(`unsupported digest ${algorithm}`);
|
|
3332
|
+
return new Uint8Array(await crypto.subtle.digest(name2, toBytes(data)));
|
|
3340
3333
|
}
|
|
3341
3334
|
|
|
3342
|
-
//
|
|
3335
|
+
// contract/validate.ts
|
|
3343
3336
|
var UNKNOWN_KIND_HINTS = [
|
|
3344
3337
|
[/^(video|vod|clip|short)s?$/i, "\u5E73\u53F0\u4E0A\u4E00\u4E2A\u666E\u901A\u7684\u89C6\u9891\u5199 onDemand\uFF0C\u4E0D\u8981\u5199\u6210 movie \u6216 file"],
|
|
3345
3338
|
[/^(song|track|music|audio)s?$/i, 'NAS \u91CC\u7684\u97F3\u4E50\u6587\u4EF6\u5199 file\uFF0Cmedia \u4E3A "audio"\uFF0C\u9996\u53D1\u4E0D\u8BA4\u6210\u6B4C\u66F2'],
|
|
@@ -3440,23 +3433,23 @@ var Checker = class {
|
|
|
3440
3433
|
object(schema, value, path, union2) {
|
|
3441
3434
|
if (!isPlainObject(value)) return this.report(path, `is ${shown(value)}, expected ${describe(schema)}`);
|
|
3442
3435
|
const kind = union2 === void 0 ? void 0 : value[union2.tag];
|
|
3443
|
-
for (const [
|
|
3444
|
-
const present = value[
|
|
3436
|
+
for (const [name2, field] of Object.entries(schema.fields)) {
|
|
3437
|
+
const present = value[name2] !== void 0 && value[name2] !== null;
|
|
3445
3438
|
if (field.kind === "optional") {
|
|
3446
|
-
if (present) this.check(field.of, value[
|
|
3439
|
+
if (present) this.check(field.of, value[name2], `${path}.${name2}`);
|
|
3447
3440
|
} else if (!present) {
|
|
3448
|
-
this.report(`${path}.${
|
|
3441
|
+
this.report(`${path}.${name2}`, `is missing; ${schema.name} requires it`, `add ${name2}: ${describe(field)}`);
|
|
3449
3442
|
} else {
|
|
3450
|
-
this.check(field, value[
|
|
3443
|
+
this.check(field, value[name2], `${path}.${name2}`);
|
|
3451
3444
|
}
|
|
3452
3445
|
}
|
|
3453
|
-
for (const
|
|
3454
|
-
if (value[
|
|
3455
|
-
const owners = union2 === void 0 ? [] : Object.entries(union2.variants).filter(([, variant]) => variant.kind === "object" && Object.hasOwn(variant.fields,
|
|
3456
|
-
const misplaced = MISPLACED_FIELD_HINTS.find((row) => row.kinds.includes(String(kind)) && row.fields.includes(
|
|
3446
|
+
for (const name2 of Object.keys(value).filter((key) => !Object.hasOwn(schema.fields, key))) {
|
|
3447
|
+
if (value[name2] === void 0) continue;
|
|
3448
|
+
const owners = union2 === void 0 ? [] : Object.entries(union2.variants).filter(([, variant]) => variant.kind === "object" && Object.hasOwn(variant.fields, name2)).map(([tag]) => tag);
|
|
3449
|
+
const misplaced = MISPLACED_FIELD_HINTS.find((row) => row.kinds.includes(String(kind)) && row.fields.includes(name2));
|
|
3457
3450
|
const where = owners.length > 0 ? `; it belongs to ${owners.join(", ")}` : "";
|
|
3458
3451
|
this.report(
|
|
3459
|
-
`${path}.${
|
|
3452
|
+
`${path}.${name2}`,
|
|
3460
3453
|
`is not a field of ${union2 === void 0 ? schema.name : `${union2.tag} ${JSON.stringify(kind)}`}${where}`,
|
|
3461
3454
|
misplaced?.hint ?? (owners.length > 0 ? `pick the ${union2.tag} that has this field, or drop it` : `drop it; ${schema.name} has ${Object.keys(schema.fields).join(", ")}`)
|
|
3462
3455
|
);
|
|
@@ -3469,18 +3462,18 @@ var Checker = class {
|
|
|
3469
3462
|
if (typeof tag !== "string" || !Object.hasOwn(schema.variants, tag)) {
|
|
3470
3463
|
return this.report(
|
|
3471
3464
|
`${path}.${schema.tag}`,
|
|
3472
|
-
`is ${shown(tag)}, expected one of ${known.map((
|
|
3465
|
+
`is ${shown(tag)}, expected one of ${known.map((name2) => JSON.stringify(name2)).join(", ")}; the App skips a ${schema.name} it does not recognize`,
|
|
3473
3466
|
hintFor(tag) ?? `pick a ${schema.tag} by the questions in choosing-a-kind.md of the krillplayer-plugin skill`
|
|
3474
3467
|
);
|
|
3475
3468
|
}
|
|
3476
3469
|
const variant = schema.variants[tag];
|
|
3477
3470
|
if (!schema.wrapped) return this.check(variant, value, path, schema);
|
|
3478
|
-
for (const
|
|
3479
|
-
if (
|
|
3471
|
+
for (const name2 of Object.keys(value)) {
|
|
3472
|
+
if (name2 !== schema.tag && name2 !== tag && value[name2] !== void 0) {
|
|
3480
3473
|
this.report(
|
|
3481
|
-
`${path}.${
|
|
3474
|
+
`${path}.${name2}`,
|
|
3482
3475
|
`is not a field of ${schema.name}; a ${schema.tag} ${JSON.stringify(tag)} entry has only ${schema.tag} and ${tag}`,
|
|
3483
|
-
Object.hasOwn(schema.variants,
|
|
3476
|
+
Object.hasOwn(schema.variants, name2) ? `set ${schema.tag}: ${JSON.stringify(name2)}, or move the object under ${tag}` : "drop it"
|
|
3484
3477
|
);
|
|
3485
3478
|
}
|
|
3486
3479
|
}
|
|
@@ -3528,7 +3521,7 @@ function validateOutput(slot, fn, output) {
|
|
|
3528
3521
|
return validate(expected.schema, output);
|
|
3529
3522
|
}
|
|
3530
3523
|
|
|
3531
|
-
//
|
|
3524
|
+
// packer/zip.ts
|
|
3532
3525
|
import { crc32 } from "node:zlib";
|
|
3533
3526
|
var DOS_DATE = 0 << 9 | 1 << 5 | 1;
|
|
3534
3527
|
var UTF8_NAMES = 2048;
|
|
@@ -3536,8 +3529,8 @@ function writeZip(entries) {
|
|
|
3536
3529
|
const locals = [];
|
|
3537
3530
|
const centrals = [];
|
|
3538
3531
|
let offset = 0;
|
|
3539
|
-
for (const { name, data } of entries) {
|
|
3540
|
-
const nameBytes = Buffer.from(
|
|
3532
|
+
for (const { name: name2, data } of entries) {
|
|
3533
|
+
const nameBytes = Buffer.from(name2, "utf8");
|
|
3541
3534
|
const crc = crc32(data);
|
|
3542
3535
|
const local = Buffer.alloc(30);
|
|
3543
3536
|
local.writeUInt32LE(67324752, 0);
|
|
@@ -3580,28 +3573,218 @@ function readZip(zip) {
|
|
|
3580
3573
|
for (let index = 0; index < zip.readUInt16LE(end + 10); index += 1) {
|
|
3581
3574
|
if (zip.readUInt32LE(position) !== 33639248) throw new Error("corrupt central directory");
|
|
3582
3575
|
const nameLength = zip.readUInt16LE(position + 28);
|
|
3583
|
-
const
|
|
3584
|
-
if (zip.readUInt16LE(position + 10) !== 0) throw new Error(`${
|
|
3576
|
+
const name2 = zip.toString("utf8", position + 46, position + 46 + nameLength);
|
|
3577
|
+
if (zip.readUInt16LE(position + 10) !== 0) throw new Error(`${name2} is compressed; plugin zips are stored only`);
|
|
3585
3578
|
const size = zip.readUInt32LE(position + 24);
|
|
3586
3579
|
const local = zip.readUInt32LE(position + 42);
|
|
3587
3580
|
const start = local + 30 + zip.readUInt16LE(local + 26) + zip.readUInt16LE(local + 28);
|
|
3588
3581
|
const data = zip.subarray(start, start + size);
|
|
3589
|
-
if (crc32(data) !== zip.readUInt32LE(position + 16)) throw new Error(`${
|
|
3590
|
-
files2.set(
|
|
3582
|
+
if (crc32(data) !== zip.readUInt32LE(position + 16)) throw new Error(`${name2} fails its CRC`);
|
|
3583
|
+
files2.set(name2, data);
|
|
3591
3584
|
position += 46 + nameLength + zip.readUInt16LE(position + 30) + zip.readUInt16LE(position + 32);
|
|
3592
3585
|
}
|
|
3593
3586
|
return files2;
|
|
3594
3587
|
}
|
|
3595
3588
|
|
|
3596
|
-
//
|
|
3589
|
+
// trial-runner/cases.ts
|
|
3597
3590
|
import { readdir, readFile as readFile2 } from "node:fs/promises";
|
|
3598
3591
|
import { join, relative } from "node:path";
|
|
3599
3592
|
|
|
3600
|
-
//
|
|
3593
|
+
// trial-runner/credentials.ts
|
|
3601
3594
|
import { readFile } from "node:fs/promises";
|
|
3595
|
+
|
|
3596
|
+
// trial-runner/json-body.ts
|
|
3597
|
+
var NotJSON = class extends Error {
|
|
3598
|
+
};
|
|
3599
|
+
var BadJSON = class extends Error {
|
|
3600
|
+
};
|
|
3601
|
+
var JSON_DEPTH = 128;
|
|
3602
|
+
var NUMBER = /-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;
|
|
3603
|
+
function parseJSONBody(text) {
|
|
3604
|
+
let index = 0;
|
|
3605
|
+
let depth = 0;
|
|
3606
|
+
const enter = () => {
|
|
3607
|
+
depth += 1;
|
|
3608
|
+
if (depth > JSON_DEPTH) throw new BadJSON(`nesting deeper than ${JSON_DEPTH}`);
|
|
3609
|
+
};
|
|
3610
|
+
const space = () => {
|
|
3611
|
+
while (index < text.length && " \n\r".includes(text[index])) index += 1;
|
|
3612
|
+
};
|
|
3613
|
+
const expect = (literal) => {
|
|
3614
|
+
if (!text.startsWith(literal, index)) throw new NotJSON();
|
|
3615
|
+
index += literal.length;
|
|
3616
|
+
};
|
|
3617
|
+
const string2 = () => {
|
|
3618
|
+
expect('"');
|
|
3619
|
+
let out = "";
|
|
3620
|
+
for (; ; ) {
|
|
3621
|
+
if (index >= text.length) throw new NotJSON();
|
|
3622
|
+
const char = text[index];
|
|
3623
|
+
const code = text.charCodeAt(index);
|
|
3624
|
+
if (char === '"') {
|
|
3625
|
+
index += 1;
|
|
3626
|
+
return out;
|
|
3627
|
+
}
|
|
3628
|
+
if (code < 32) throw new NotJSON();
|
|
3629
|
+
if (char !== "\\") {
|
|
3630
|
+
out += char;
|
|
3631
|
+
index += 1;
|
|
3632
|
+
continue;
|
|
3633
|
+
}
|
|
3634
|
+
const escape = text[index + 1];
|
|
3635
|
+
index += 2;
|
|
3636
|
+
const simple = { '"': '"', "\\": "\\", "/": "/", b: "\b", f: "\f", n: "\n", r: "\r", t: " " };
|
|
3637
|
+
if (escape in simple) {
|
|
3638
|
+
out += simple[escape];
|
|
3639
|
+
continue;
|
|
3640
|
+
}
|
|
3641
|
+
if (escape !== "u" || !/^[0-9A-Fa-f]{4}$/.test(text.slice(index, index + 4))) throw new NotJSON();
|
|
3642
|
+
out += String.fromCharCode(parseInt(text.slice(index, index + 4), 16));
|
|
3643
|
+
index += 4;
|
|
3644
|
+
}
|
|
3645
|
+
};
|
|
3646
|
+
const value = () => {
|
|
3647
|
+
space();
|
|
3648
|
+
const char = text[index];
|
|
3649
|
+
if (char === "{") {
|
|
3650
|
+
index += 1;
|
|
3651
|
+
enter();
|
|
3652
|
+
const object2 = /* @__PURE__ */ new Map();
|
|
3653
|
+
space();
|
|
3654
|
+
if (text[index] === "}") {
|
|
3655
|
+
index += 1;
|
|
3656
|
+
depth -= 1;
|
|
3657
|
+
return object2;
|
|
3658
|
+
}
|
|
3659
|
+
for (; ; ) {
|
|
3660
|
+
space();
|
|
3661
|
+
const key = string2();
|
|
3662
|
+
space();
|
|
3663
|
+
expect(":");
|
|
3664
|
+
const entry = value();
|
|
3665
|
+
if (object2.has(key)) throw new BadJSON("duplicate key");
|
|
3666
|
+
object2.set(key, entry);
|
|
3667
|
+
space();
|
|
3668
|
+
if (text[index] === ",") {
|
|
3669
|
+
index += 1;
|
|
3670
|
+
continue;
|
|
3671
|
+
}
|
|
3672
|
+
expect("}");
|
|
3673
|
+
depth -= 1;
|
|
3674
|
+
return object2;
|
|
3675
|
+
}
|
|
3676
|
+
}
|
|
3677
|
+
if (char === "[") {
|
|
3678
|
+
index += 1;
|
|
3679
|
+
enter();
|
|
3680
|
+
const array2 = [];
|
|
3681
|
+
space();
|
|
3682
|
+
if (text[index] === "]") {
|
|
3683
|
+
index += 1;
|
|
3684
|
+
depth -= 1;
|
|
3685
|
+
return array2;
|
|
3686
|
+
}
|
|
3687
|
+
for (; ; ) {
|
|
3688
|
+
array2.push(value());
|
|
3689
|
+
space();
|
|
3690
|
+
if (text[index] === ",") {
|
|
3691
|
+
index += 1;
|
|
3692
|
+
continue;
|
|
3693
|
+
}
|
|
3694
|
+
expect("]");
|
|
3695
|
+
depth -= 1;
|
|
3696
|
+
return array2;
|
|
3697
|
+
}
|
|
3698
|
+
}
|
|
3699
|
+
if (char === '"') return string2();
|
|
3700
|
+
for (const [literal, result2] of [["true", true], ["false", false], ["null", null]]) {
|
|
3701
|
+
if (text.startsWith(literal, index)) {
|
|
3702
|
+
index += literal.length;
|
|
3703
|
+
return result2;
|
|
3704
|
+
}
|
|
3705
|
+
}
|
|
3706
|
+
NUMBER.lastIndex = index;
|
|
3707
|
+
const match = NUMBER.exec(text);
|
|
3708
|
+
if (match === null) throw new NotJSON();
|
|
3709
|
+
index += match[0].length;
|
|
3710
|
+
const number2 = Number(match[0]);
|
|
3711
|
+
if (!Number.isFinite(number2)) throw new BadJSON("number is not a finite double");
|
|
3712
|
+
return number2;
|
|
3713
|
+
};
|
|
3714
|
+
const result = value();
|
|
3715
|
+
space();
|
|
3716
|
+
if (index !== text.length) throw new NotJSON();
|
|
3717
|
+
const loneSurrogate = (item) => {
|
|
3718
|
+
if (typeof item === "string") return !item.isWellFormed();
|
|
3719
|
+
if (Array.isArray(item)) return item.some(loneSurrogate);
|
|
3720
|
+
if (item instanceof Map) return [...item].some(([key, entry]) => !key.isWellFormed() || loneSurrogate(entry));
|
|
3721
|
+
return false;
|
|
3722
|
+
};
|
|
3723
|
+
if (loneSurrogate(result)) throw new BadJSON("lone surrogate in a string");
|
|
3724
|
+
return result;
|
|
3725
|
+
}
|
|
3726
|
+
function bodyKind(bytes2) {
|
|
3727
|
+
if (bytes2 === null || bytes2.length === 0) return { kind: "none" };
|
|
3728
|
+
let text;
|
|
3729
|
+
try {
|
|
3730
|
+
text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes2);
|
|
3731
|
+
} catch {
|
|
3732
|
+
return { kind: "bytes", bytes: bytes2 };
|
|
3733
|
+
}
|
|
3734
|
+
if (text.startsWith("\uFEFF")) return { kind: "bad", reason: "starts with a byte order mark" };
|
|
3735
|
+
try {
|
|
3736
|
+
return { kind: "json", value: parseJSONBody(text) };
|
|
3737
|
+
} catch (error) {
|
|
3738
|
+
if (error instanceof BadJSON) return { kind: "bad", reason: error.message };
|
|
3739
|
+
if (error instanceof NotJSON) return { kind: "text", text };
|
|
3740
|
+
throw error;
|
|
3741
|
+
}
|
|
3742
|
+
}
|
|
3743
|
+
function canonicalJSON(value) {
|
|
3744
|
+
if (value instanceof Map) {
|
|
3745
|
+
return `{${[...value.keys()].sort().map((key) => `${JSON.stringify(key)}:${canonicalJSON(value.get(key))}`).join(",")}}`;
|
|
3746
|
+
}
|
|
3747
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJSON).join(",")}]`;
|
|
3748
|
+
return JSON.stringify(value);
|
|
3749
|
+
}
|
|
3750
|
+
function writtenJSON(value) {
|
|
3751
|
+
if (value instanceof Map) return `{${[...value].map(([key, entry]) => `${JSON.stringify(key)}:${writtenJSON(entry)}`).join(",")}}`;
|
|
3752
|
+
if (Array.isArray(value)) return `[${value.map(writtenJSON).join(",")}]`;
|
|
3753
|
+
return JSON.stringify(value);
|
|
3754
|
+
}
|
|
3755
|
+
function redactedJSON(value, isSecretName2, redactString2) {
|
|
3756
|
+
if (typeof value === "string") return redactString2(value);
|
|
3757
|
+
if (Array.isArray(value)) return value.map((entry) => redactedJSON(entry, isSecretName2, redactString2));
|
|
3758
|
+
if (value instanceof Map) {
|
|
3759
|
+
return new Map([...value].map(([key, entry]) => [
|
|
3760
|
+
key,
|
|
3761
|
+
isSecretName2(key) && entry !== null && typeof entry !== "object" ? "REDACTED" : redactedJSON(entry, isSecretName2, redactString2)
|
|
3762
|
+
]));
|
|
3763
|
+
}
|
|
3764
|
+
return value;
|
|
3765
|
+
}
|
|
3766
|
+
|
|
3767
|
+
// trial-runner/secret-names.ts
|
|
3768
|
+
var SECRET_HEADERS = ["cookie", "set-cookie", "authorization", "proxy-authorization", "x-csrf-token", "x-xsrf-token", "x-emby-token"];
|
|
3769
|
+
var SECRET_NAME_PATTERN = "^(?:access_?key|api_?key|access_?token|refresh_?token|id_?token|token|\\w+_token|subsonic_?token|sessdata|bili_jct|csrf|\\w*session\\w*|password|passwd|pw|secret|ticket|auth|authorization|cookie|dedeuserid|uin|openid|unionid)$";
|
|
3770
|
+
var SPACE = "\\x09\\x0A\\x0B\\x0C\\x0D\\x20";
|
|
3771
|
+
var QUERY_PATTERN = `^\\??[^=&${SPACE}?]+=[^&${SPACE}]*(?:&[^=&${SPACE}]+=[^&${SPACE}]*)+$`;
|
|
3772
|
+
var FORM_PATTERN = `^[^=&${SPACE}]+=[^&]*(?:&[^=&${SPACE}]+=[^&]*)*$`;
|
|
3773
|
+
var asciiLowercased = (value) => value.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
|
|
3774
|
+
var headers = new Set(SECRET_HEADERS);
|
|
3775
|
+
var name = new RegExp(SECRET_NAME_PATTERN);
|
|
3776
|
+
var isSecretName = (value) => {
|
|
3777
|
+
const lower2 = asciiLowercased(value);
|
|
3778
|
+
return headers.has(lower2) || name.test(lower2);
|
|
3779
|
+
};
|
|
3780
|
+
var isSecretParam = (value, names) => isSecretName(value) || names.has("u") && (value === "t" && names.has("s") || value === "p");
|
|
3781
|
+
|
|
3782
|
+
// trial-runner/credentials.ts
|
|
3602
3783
|
var REDACTED = "REDACTED";
|
|
3603
|
-
|
|
3604
|
-
|
|
3784
|
+
function fakeValue(value, index) {
|
|
3785
|
+
return /^\d+$/.test(value) ? String(9 - index % 9).repeat(value.length) : REDACTED;
|
|
3786
|
+
}
|
|
3787
|
+
var isFakeId = (value) => /^(\d)\1*$/.test(value);
|
|
3605
3788
|
var SECRET_VALUES = [
|
|
3606
3789
|
/\bSESSDATA=(?!REDACTED\b)[^;&\s"]{8,}/,
|
|
3607
3790
|
/\bbili_jct=[0-9a-f]{16,}/i,
|
|
@@ -3609,63 +3792,76 @@ var SECRET_VALUES = [
|
|
|
3609
3792
|
/\beyJ[\w-]{8,}\.eyJ[\w-]{8,}\.[\w-]+/,
|
|
3610
3793
|
/\b(?:access_key|access_token)=[\w.-]{16,}/
|
|
3611
3794
|
];
|
|
3612
|
-
var isSecretName = (name) => SECRET_HEADERS.has(name.toLowerCase()) || SECRET_NAME.test(name);
|
|
3613
|
-
var isSubsonicSecret = (name, params) => params.has("u") && (name === "t" && params.has("s") || name === "p");
|
|
3614
|
-
var isSecretParam = (name, params) => isSecretName(name) || isSubsonicSecret(name, params);
|
|
3615
3795
|
var redactSetCookie = (lines) => lines.split("\n").map((line) => line.replace(/^([^=;]*)=[^;]*/, `$1=${REDACTED}`)).join("\n");
|
|
3616
3796
|
var isRedactedSetCookie = (lines) => lines.split("\n").every((line) => new RegExp(`^[^=;]*=${REDACTED}(;|$)`).test(line));
|
|
3617
|
-
function redactHeaders(
|
|
3618
|
-
return Object.fromEntries(Object.entries(
|
|
3619
|
-
if (
|
|
3620
|
-
return isSecretName(
|
|
3797
|
+
function redactHeaders(headers2) {
|
|
3798
|
+
return Object.fromEntries(Object.entries(headers2).flatMap(([name2, value]) => {
|
|
3799
|
+
if (name2.toLowerCase() === "set-cookie") return [[name2, redactSetCookie(value)]];
|
|
3800
|
+
return isSecretName(name2) ? [] : [[name2, value]];
|
|
3621
3801
|
}));
|
|
3622
3802
|
}
|
|
3623
|
-
|
|
3624
|
-
|
|
3625
|
-
|
|
3626
|
-
|
|
3627
|
-
|
|
3628
|
-
|
|
3629
|
-
}
|
|
3803
|
+
var pairName = (pair) => {
|
|
3804
|
+
const raw = pair.split("=", 1)[0].replaceAll("+", " ");
|
|
3805
|
+
try {
|
|
3806
|
+
return decodeURIComponent(raw);
|
|
3807
|
+
} catch {
|
|
3808
|
+
return raw;
|
|
3630
3809
|
}
|
|
3631
|
-
|
|
3810
|
+
};
|
|
3811
|
+
function redactPairs(text) {
|
|
3812
|
+
const pairs = text.split("&");
|
|
3813
|
+
const names = new Set(pairs.map(pairName));
|
|
3814
|
+
let changed = false;
|
|
3815
|
+
const rewritten = pairs.map((pair) => {
|
|
3816
|
+
const equals = pair.indexOf("=");
|
|
3817
|
+
if (!isSecretParam(pairName(pair), names) || equals >= 0 && pair.slice(equals + 1) === REDACTED) return pair;
|
|
3818
|
+
changed = true;
|
|
3819
|
+
return `${equals < 0 ? pair : pair.slice(0, equals)}=${REDACTED}`;
|
|
3820
|
+
});
|
|
3821
|
+
return changed ? rewritten.join("&") : text;
|
|
3632
3822
|
}
|
|
3633
3823
|
function redactUrl(url) {
|
|
3634
|
-
const
|
|
3635
|
-
|
|
3636
|
-
|
|
3637
|
-
|
|
3824
|
+
const start = url.indexOf("?");
|
|
3825
|
+
if (start < 0) return url;
|
|
3826
|
+
const hash = url.indexOf("#");
|
|
3827
|
+
const end = hash < 0 ? url.length : hash;
|
|
3828
|
+
if (start > end) return url;
|
|
3829
|
+
return `${url.slice(0, start + 1)}${redactPairs(url.slice(start + 1, end))}${url.slice(end)}`;
|
|
3830
|
+
}
|
|
3831
|
+
var QUERY = new RegExp(QUERY_PATTERN);
|
|
3832
|
+
var FORM = new RegExp(FORM_PATTERN);
|
|
3638
3833
|
function queryOf(value) {
|
|
3639
3834
|
return QUERY.test(value) ? new URLSearchParams(value.replace(/^\?/, "")) : void 0;
|
|
3640
3835
|
}
|
|
3641
3836
|
function redactString(value) {
|
|
3642
|
-
if (/^https?:\/\//.test(value)
|
|
3643
|
-
|
|
3644
|
-
|
|
3645
|
-
return `${value.startsWith("?") ? "?" : ""}${params.toString()}`;
|
|
3646
|
-
}
|
|
3647
|
-
function redactJSON(value) {
|
|
3648
|
-
if (typeof value === "string") return redactString(value);
|
|
3649
|
-
if (Array.isArray(value)) return value.map(redactJSON);
|
|
3650
|
-
if (typeof value === "object" && value !== null) {
|
|
3651
|
-
return Object.fromEntries(Object.entries(value).map(([key, entry]) => [
|
|
3652
|
-
key,
|
|
3653
|
-
isSecretName(key) && entry !== null && typeof entry !== "object" ? REDACTED : redactJSON(entry)
|
|
3654
|
-
]));
|
|
3655
|
-
}
|
|
3656
|
-
return value;
|
|
3837
|
+
if (/^https?:\/\//.test(value)) return redactUrl(value);
|
|
3838
|
+
if (!QUERY.test(value)) return value;
|
|
3839
|
+
return value.startsWith("?") ? `?${redactPairs(value.slice(1))}` : redactPairs(value);
|
|
3657
3840
|
}
|
|
3658
|
-
var FORM = /^[^=&\s]+=[^&]*(?:&[^=&\s]+=[^&]*)*$/;
|
|
3659
3841
|
function redactBody(body) {
|
|
3660
3842
|
if (typeof body !== "string") return body;
|
|
3661
|
-
|
|
3662
|
-
|
|
3663
|
-
const redacted =
|
|
3664
|
-
return redacted ===
|
|
3665
|
-
}
|
|
3666
|
-
|
|
3667
|
-
|
|
3668
|
-
|
|
3843
|
+
const kind = bodyKind(bodyFromJSON(body));
|
|
3844
|
+
if (kind.kind === "json") {
|
|
3845
|
+
const redacted = redactedJSON(kind.value, isSecretName, redactString);
|
|
3846
|
+
return canonicalJSON(redacted) === canonicalJSON(kind.value) ? body : writtenJSON(redacted);
|
|
3847
|
+
}
|
|
3848
|
+
if (kind.kind === "text") return FORM.test(kind.text) ? redactPairs(kind.text) : body;
|
|
3849
|
+
return body;
|
|
3850
|
+
}
|
|
3851
|
+
var unmatchable = 0;
|
|
3852
|
+
function bodyKey(body) {
|
|
3853
|
+
const kind = bodyKind(bodyFromJSON(body));
|
|
3854
|
+
switch (kind.kind) {
|
|
3855
|
+
case "none":
|
|
3856
|
+
return "";
|
|
3857
|
+
case "bytes":
|
|
3858
|
+
return `bytes:${Buffer.from(kind.bytes).toString("base64")}`;
|
|
3859
|
+
case "bad":
|
|
3860
|
+
return `bad:${unmatchable += 1}`;
|
|
3861
|
+
case "json":
|
|
3862
|
+
return `json:${canonicalJSON(redactedJSON(kind.value, isSecretName, redactString))}`;
|
|
3863
|
+
case "text":
|
|
3864
|
+
return `text:${FORM.test(kind.text) ? redactPairs(kind.text) : kind.text}`;
|
|
3669
3865
|
}
|
|
3670
3866
|
}
|
|
3671
3867
|
function redactExchange({ request, response }) {
|
|
@@ -3680,18 +3876,14 @@ function redactExchange({ request, response }) {
|
|
|
3680
3876
|
}
|
|
3681
3877
|
};
|
|
3682
3878
|
}
|
|
3683
|
-
function redactCredentials(credentials) {
|
|
3684
|
-
if (typeof credentials !== "object" || credentials === null) return credentials;
|
|
3685
|
-
return Object.fromEntries(Object.entries(credentials).map(([key]) => [key, REDACTED]));
|
|
3686
|
-
}
|
|
3687
3879
|
function findingsIn(value, path, findings) {
|
|
3688
3880
|
if (typeof value === "string") {
|
|
3689
3881
|
const text = value;
|
|
3690
3882
|
if (SECRET_VALUES.some((pattern) => pattern.test(text))) findings.push(`${path}: credential-like value`);
|
|
3691
3883
|
const query = /^https?:\/\//.test(text) && URL.canParse(text) ? new URL(text).searchParams : queryOf(text);
|
|
3692
3884
|
if (query !== void 0) {
|
|
3693
|
-
for (const [
|
|
3694
|
-
if (isSecretParam(
|
|
3885
|
+
for (const [name2, entry] of query) {
|
|
3886
|
+
if (isSecretParam(name2, query) && entry !== REDACTED && entry !== "") findings.push(`${path}: query parameter ${name2}`);
|
|
3695
3887
|
}
|
|
3696
3888
|
}
|
|
3697
3889
|
return;
|
|
@@ -3707,7 +3899,7 @@ function findingsIn(value, path, findings) {
|
|
|
3707
3899
|
return;
|
|
3708
3900
|
}
|
|
3709
3901
|
for (const [key, entry] of Object.entries(value)) {
|
|
3710
|
-
const redacted = entry === REDACTED || key.toLowerCase() === "set-cookie" && typeof entry === "string" && isRedactedSetCookie(entry);
|
|
3902
|
+
const redacted = entry === REDACTED || typeof entry === "string" && isFakeId(entry) || key.toLowerCase() === "set-cookie" && typeof entry === "string" && isRedactedSetCookie(entry);
|
|
3711
3903
|
if (isSecretName(key) && typeof entry === "string" && !redacted && entry !== "") {
|
|
3712
3904
|
findings.push(`${path}.${key}: ${key}`);
|
|
3713
3905
|
}
|
|
@@ -3731,7 +3923,7 @@ async function scanDirectories(directories) {
|
|
|
3731
3923
|
return { files: files2, findings };
|
|
3732
3924
|
}
|
|
3733
3925
|
|
|
3734
|
-
//
|
|
3926
|
+
// trial-runner/cases.ts
|
|
3735
3927
|
function bytesToJSON(bytes2) {
|
|
3736
3928
|
return { $bytes: Buffer.from(bytes2).toString("base64") };
|
|
3737
3929
|
}
|
|
@@ -3741,8 +3933,8 @@ function isBytesJSON(value) {
|
|
|
3741
3933
|
function bodyToJSON(bytes2) {
|
|
3742
3934
|
if (bytes2 === void 0 || bytes2.length === 0) return void 0;
|
|
3743
3935
|
try {
|
|
3744
|
-
const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes2);
|
|
3745
|
-
return /[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(text) ? bytesToJSON(bytes2) : text;
|
|
3936
|
+
const text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes2);
|
|
3937
|
+
return /[\u0000-\u0008\u000b\u000c\u000e-\u001f\uFEFF]/.test(text) ? bytesToJSON(bytes2) : text;
|
|
3746
3938
|
} catch {
|
|
3747
3939
|
return bytesToJSON(bytes2);
|
|
3748
3940
|
}
|
|
@@ -3787,11 +3979,11 @@ function requestOf(url, init) {
|
|
|
3787
3979
|
return { method: init.method ?? "GET", url, ...body === void 0 ? {} : { body } };
|
|
3788
3980
|
}
|
|
3789
3981
|
function responseOf(response) {
|
|
3790
|
-
const
|
|
3791
|
-
return new Response(bodyFromJSON(response.body), { status: response.status, headers });
|
|
3982
|
+
const headers2 = Object.entries(response.headers).flatMap(([name2, value]) => name2.toLowerCase() === "set-cookie" ? value.split("\n").map((line) => [name2, line]) : [[name2, value]]);
|
|
3983
|
+
return new Response(bodyFromJSON(response.body), { status: response.status, headers: headers2 });
|
|
3792
3984
|
}
|
|
3793
|
-
var canonicalHeaders = (
|
|
3794
|
-
var requestKey = ({ method, url, body }) => `${method} ${url} ${
|
|
3985
|
+
var canonicalHeaders = (headers2) => JSON.stringify(Object.entries(headers2 ?? {}).map(([name2, value]) => [name2.toLowerCase(), value]).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
|
|
3986
|
+
var requestKey = ({ method, url, body }) => `${method} ${url} ${bodyKey(body)}`;
|
|
3795
3987
|
function replayFetch(exchanges) {
|
|
3796
3988
|
const pending = [...exchanges];
|
|
3797
3989
|
const unrecorded = [];
|
|
@@ -3815,32 +4007,38 @@ function replayFetch(exchanges) {
|
|
|
3815
4007
|
var TRANSPORT_HEADERS = /* @__PURE__ */ new Set(["content-encoding", "content-length", "transfer-encoding", "connection", "keep-alive"]);
|
|
3816
4008
|
function recordingFetch(fetch) {
|
|
3817
4009
|
const exchanges = [];
|
|
4010
|
+
const unacceptable = [];
|
|
3818
4011
|
const record = async (url, init) => {
|
|
4012
|
+
const sent = requestOf(url, init);
|
|
4013
|
+
const kind = bodyKind(bodyFromJSON(sent.body));
|
|
4014
|
+
if (kind.kind === "bad") unacceptable.push(`request ${exchanges.length + 1} (${sent.method}): ${kind.reason}`);
|
|
3819
4015
|
const response = await fetch(url, init);
|
|
3820
4016
|
const body = bodyToJSON(new Uint8Array(await response.arrayBuffer()));
|
|
3821
4017
|
const recorded = {
|
|
3822
4018
|
status: response.status,
|
|
3823
|
-
headers: Object.fromEntries(Object.entries(responseHeaders(response, url)).filter(([
|
|
4019
|
+
headers: Object.fromEntries(Object.entries(responseHeaders(response, url)).filter(([name2]) => !TRANSPORT_HEADERS.has(name2))),
|
|
3824
4020
|
...body === void 0 ? {} : { body }
|
|
3825
4021
|
};
|
|
3826
4022
|
exchanges.push(redactExchange({ request: requestOf(url, init), response: recorded }));
|
|
3827
4023
|
return responseOf(recorded);
|
|
3828
4024
|
};
|
|
3829
|
-
return { fetch: record, exchanges };
|
|
4025
|
+
return { fetch: record, exchanges, unacceptable };
|
|
3830
4026
|
}
|
|
3831
4027
|
async function jsonFiles(directory) {
|
|
3832
4028
|
const entries = await readdir(directory, { recursive: true, withFileTypes: true });
|
|
3833
4029
|
return entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json") && !entry.parentPath.includes("node_modules")).map((entry) => join(entry.parentPath, entry.name)).sort();
|
|
3834
4030
|
}
|
|
4031
|
+
var BYTE_ORDER_MARK_IN_CASE = "case file holds U+FEFF, which the Swift kernel's JSON reader drops; keep such text as $bytes";
|
|
4032
|
+
var holdsByteOrderMark = (raw) => raw.includes("\uFEFF") || /\\u[fF][eE][fF][fF]/.test(raw);
|
|
3835
4033
|
async function readCases(directory) {
|
|
3836
4034
|
const files2 = await jsonFiles(directory);
|
|
3837
|
-
return Promise.all(files2.map(async (file) =>
|
|
3838
|
-
|
|
3839
|
-
data: JSON.parse(
|
|
3840
|
-
}))
|
|
4035
|
+
return Promise.all(files2.map(async (file) => {
|
|
4036
|
+
const raw = await readFile2(file, "utf8");
|
|
4037
|
+
return { name: relative(directory, file), data: JSON.parse(raw), byteOrderMark: holdsByteOrderMark(raw) };
|
|
4038
|
+
}));
|
|
3841
4039
|
}
|
|
3842
4040
|
|
|
3843
|
-
//
|
|
4041
|
+
// trial-runner/engine.ts
|
|
3844
4042
|
import { execFile, spawn } from "node:child_process";
|
|
3845
4043
|
import { createHash } from "node:crypto";
|
|
3846
4044
|
import { constants } from "node:fs";
|
|
@@ -3851,7 +4049,7 @@ import { dirname, join as join2, relative as relative2 } from "node:path";
|
|
|
3851
4049
|
import { fileURLToPath } from "node:url";
|
|
3852
4050
|
import { promisify } from "node:util";
|
|
3853
4051
|
|
|
3854
|
-
//
|
|
4052
|
+
// host/globals.ts
|
|
3855
4053
|
var ECMASCRIPT_GLOBALS = [
|
|
3856
4054
|
"globalThis",
|
|
3857
4055
|
"Infinity",
|
|
@@ -3916,7 +4114,7 @@ var ECMASCRIPT_GLOBALS = [
|
|
|
3916
4114
|
var HOST_GLOBALS = ["TextEncoder", "TextDecoder", "console"];
|
|
3917
4115
|
var PLUGIN_GLOBALS = /* @__PURE__ */ new Set([...ECMASCRIPT_GLOBALS, ...HOST_GLOBALS]);
|
|
3918
4116
|
|
|
3919
|
-
//
|
|
4117
|
+
// trial-runner/wire.ts
|
|
3920
4118
|
var MARKER = "\0";
|
|
3921
4119
|
function encode(value) {
|
|
3922
4120
|
const parts = [];
|
|
@@ -3954,12 +4152,12 @@ function decode(json, blob) {
|
|
|
3954
4152
|
if (Array.isArray(item)) return item.map(revive);
|
|
3955
4153
|
const names = Object.keys(item);
|
|
3956
4154
|
if (names.length === 1 && names[0] === MARKER) return parts[item[MARKER]];
|
|
3957
|
-
return Object.fromEntries(names.map((
|
|
4155
|
+
return Object.fromEntries(names.map((name2) => [name2, revive(item[name2])]));
|
|
3958
4156
|
};
|
|
3959
4157
|
return revive(message);
|
|
3960
4158
|
}
|
|
3961
4159
|
|
|
3962
|
-
//
|
|
4160
|
+
// trial-runner/engine.ts
|
|
3963
4161
|
var here = dirname(fileURLToPath(import.meta.url));
|
|
3964
4162
|
var run3 = promisify(execFile);
|
|
3965
4163
|
var KERNEL_LIMITS = {
|
|
@@ -4004,7 +4202,7 @@ async function executable(file) {
|
|
|
4004
4202
|
return false;
|
|
4005
4203
|
}
|
|
4006
4204
|
}
|
|
4007
|
-
var environment = (
|
|
4205
|
+
var environment = (name2) => process.env[name2] || void 0;
|
|
4008
4206
|
async function build() {
|
|
4009
4207
|
const quickjs = join2(kernelDirectory(), "Sources/CQuickJS");
|
|
4010
4208
|
const compiler = environment("CC") ?? "cc";
|
|
@@ -4065,7 +4263,7 @@ var prelude;
|
|
|
4065
4263
|
function preludeSource() {
|
|
4066
4264
|
const path = join2(kernelDirectory(), "Sources/Kernel/PluginPrelude.js");
|
|
4067
4265
|
prelude ??= readFile3(path, "utf8").then(
|
|
4068
|
-
(template) => template.replaceAll("__GLOBALS__", `[${[...PLUGIN_GLOBALS].sort().map((
|
|
4266
|
+
(template) => template.replaceAll("__GLOBALS__", `[${[...PLUGIN_GLOBALS].sort().map((name2) => JSON.stringify(name2)).join(", ")}]`),
|
|
4069
4267
|
(error) => {
|
|
4070
4268
|
throw new EngineFailure(`could not read the plugin prelude ${path}: ${error.message}`);
|
|
4071
4269
|
}
|
|
@@ -4227,12 +4425,12 @@ var CALLS = {
|
|
|
4227
4425
|
};
|
|
4228
4426
|
var STARTS = {
|
|
4229
4427
|
"http.request": (k, [request]) => k.http.request(request),
|
|
4230
|
-
"appKeys.get": (k, [
|
|
4428
|
+
"appKeys.get": (k, [name2]) => k.appKeys.get(name2),
|
|
4231
4429
|
"formats.xmltv.channels": (k, [source]) => k.formats.xmltv.channels(source),
|
|
4232
4430
|
"formats.xmltv.programmes": (k, [source, query]) => k.formats.xmltv.programmes(source, query),
|
|
4233
4431
|
"metadata.search": (k, [kind, query, options]) => k.metadata.search(kind, query, options),
|
|
4234
4432
|
"metadata.get": (k, [kind, ids]) => k.metadata.get(kind, ids),
|
|
4235
|
-
"metadata.list": (k, [
|
|
4433
|
+
"metadata.list": (k, [name2, kind, options]) => k.metadata.list(name2, kind, options),
|
|
4236
4434
|
"files.list": (k, [path, cursor]) => k.files.list(path, cursor ?? void 0),
|
|
4237
4435
|
"files.stat": (k, [path]) => k.files.stat(path),
|
|
4238
4436
|
"files.read": (k, [path, offset, length]) => k.files.read(path, offset, length)
|
|
@@ -4349,15 +4547,15 @@ var EngineContext = class _EngineContext {
|
|
|
4349
4547
|
this.#settled.set(message.call, message.ok === true ? { ok: true, value: message.value ?? null } : { ok: false, error: failure(message) });
|
|
4350
4548
|
return null;
|
|
4351
4549
|
}
|
|
4352
|
-
const
|
|
4353
|
-
const capability =
|
|
4550
|
+
const name2 = String(message.name);
|
|
4551
|
+
const capability = name2.split(".")[0];
|
|
4354
4552
|
if (this.#slot === "status" && !STATUS_SLOT_CAPABILITIES.has(capability)) {
|
|
4355
4553
|
throw new TypeError(`krillplayer.${capability} is not available to the status slot`);
|
|
4356
4554
|
}
|
|
4357
|
-
if (message.op === "start" && Object.hasOwn(STARTS,
|
|
4555
|
+
if (message.op === "start" && Object.hasOwn(STARTS, name2)) {
|
|
4358
4556
|
const id = Number(message.id);
|
|
4359
4557
|
this.#inFlight += 1;
|
|
4360
|
-
STARTS[
|
|
4558
|
+
STARTS[name2](this.#krillplayer, args).then(
|
|
4361
4559
|
(value) => this.#complete({ id, ok: true, value }),
|
|
4362
4560
|
(error) => this.#complete({
|
|
4363
4561
|
id,
|
|
@@ -4368,8 +4566,8 @@ var EngineContext = class _EngineContext {
|
|
|
4368
4566
|
);
|
|
4369
4567
|
return null;
|
|
4370
4568
|
}
|
|
4371
|
-
if (message.op === "call" && Object.hasOwn(CALLS,
|
|
4372
|
-
throw new TypeError(`malformed message from the plugin context: ${message.op} ${
|
|
4569
|
+
if (message.op === "call" && Object.hasOwn(CALLS, name2)) return await CALLS[name2](this.#krillplayer, args) ?? null;
|
|
4570
|
+
throw new TypeError(`malformed message from the plugin context: ${message.op} ${name2}`);
|
|
4373
4571
|
}
|
|
4374
4572
|
#complete(completion) {
|
|
4375
4573
|
this.#completions.push(completion);
|
|
@@ -4385,7 +4583,7 @@ function structuredError(error) {
|
|
|
4385
4583
|
return error instanceof PluginFailure ? error.plugin : { kind: "other" };
|
|
4386
4584
|
}
|
|
4387
4585
|
|
|
4388
|
-
//
|
|
4586
|
+
// trial-runner/files.ts
|
|
4389
4587
|
var FAILURES = { loginRequired: "accessDenied", retryable: "unreachable" };
|
|
4390
4588
|
function scriptedFiles(script = {}) {
|
|
4391
4589
|
const problems = [];
|
|
@@ -4429,8 +4627,8 @@ function scriptedFiles(script = {}) {
|
|
|
4429
4627
|
return node;
|
|
4430
4628
|
};
|
|
4431
4629
|
const content = (node) => new Uint8Array(bodyFromJSON(node.file.content) ?? []);
|
|
4432
|
-
const entry = (
|
|
4433
|
-
name,
|
|
4630
|
+
const entry = (name2, path, node) => ({
|
|
4631
|
+
name: name2,
|
|
4434
4632
|
path,
|
|
4435
4633
|
isDirectory: node.directory,
|
|
4436
4634
|
...node.directory ? {} : { size: node.file.size ?? content(node).length },
|
|
@@ -4448,7 +4646,7 @@ function scriptedFiles(script = {}) {
|
|
|
4448
4646
|
const start = Number(cursor ?? "0");
|
|
4449
4647
|
const end = script.pageSize === void 0 ? names.length : start + script.pageSize;
|
|
4450
4648
|
return {
|
|
4451
|
-
entries: names.slice(start, end).map((
|
|
4649
|
+
entries: names.slice(start, end).map((name2) => entry(name2, path === "" ? name2 : `${path}/${name2}`, node.children.get(name2))),
|
|
4452
4650
|
...end < names.length ? { next: String(end) } : {}
|
|
4453
4651
|
};
|
|
4454
4652
|
},
|
|
@@ -4466,7 +4664,7 @@ function scriptedFiles(script = {}) {
|
|
|
4466
4664
|
return { service, problems: () => [...problems] };
|
|
4467
4665
|
}
|
|
4468
4666
|
|
|
4469
|
-
//
|
|
4667
|
+
// trial-runner/metadata.ts
|
|
4470
4668
|
function scriptedMetadata(script = []) {
|
|
4471
4669
|
const pending = [...script];
|
|
4472
4670
|
const problems = [];
|
|
@@ -4517,9 +4715,9 @@ function scriptedMetadata(script = []) {
|
|
|
4517
4715
|
const found = validate(Work, reply, "reply");
|
|
4518
4716
|
return found.length > 0 ? malformed(`scripted metadata reply is not a Work: ${found.join("; ")}`) : work(reply);
|
|
4519
4717
|
},
|
|
4520
|
-
async list(
|
|
4521
|
-
checkList(
|
|
4522
|
-
return page(answer({ call: "list", name, kind, ...optional3({ ...filter, cursor }) }));
|
|
4718
|
+
async list(name2, kind, filter, cursor) {
|
|
4719
|
+
checkList(name2, kind, filter);
|
|
4720
|
+
return page(answer({ call: "list", name: name2, kind, ...optional3({ ...filter, cursor }) }));
|
|
4523
4721
|
}
|
|
4524
4722
|
};
|
|
4525
4723
|
return {
|
|
@@ -4532,12 +4730,12 @@ function optional3(fields) {
|
|
|
4532
4730
|
return Object.fromEntries(Object.entries(fields).filter((entry) => entry[1] !== void 0));
|
|
4533
4731
|
}
|
|
4534
4732
|
|
|
4535
|
-
//
|
|
4733
|
+
// trial-runner/static-check.ts
|
|
4536
4734
|
import { Linter } from "eslint";
|
|
4537
4735
|
var globalsRule = {
|
|
4538
4736
|
create(context) {
|
|
4539
|
-
const reportName = (node,
|
|
4540
|
-
if (!PLUGIN_GLOBALS.has(
|
|
4737
|
+
const reportName = (node, name2) => {
|
|
4738
|
+
if (!PLUGIN_GLOBALS.has(name2)) context.report({ node, message: `global ${name2} is not in the plugin globals allowlist` });
|
|
4541
4739
|
};
|
|
4542
4740
|
return {
|
|
4543
4741
|
MemberExpression(node) {
|
|
@@ -4583,47 +4781,47 @@ function checkManifest(manifest) {
|
|
|
4583
4781
|
const problems = [];
|
|
4584
4782
|
for (const parameter of parameters) {
|
|
4585
4783
|
if (typeof parameter !== "object" || parameter === null) continue;
|
|
4586
|
-
const { name, dependsOn, visibleWhen } = parameter;
|
|
4784
|
+
const { name: name2, dependsOn, visibleWhen } = parameter;
|
|
4587
4785
|
const used = [
|
|
4588
|
-
["declares",
|
|
4786
|
+
["declares", name2],
|
|
4589
4787
|
...(Array.isArray(dependsOn) ? dependsOn : []).map((item) => ["depends on", item]),
|
|
4590
4788
|
...(Array.isArray(visibleWhen) ? visibleWhen : []).map((item) => ["is shown by", item?.name])
|
|
4591
4789
|
];
|
|
4592
4790
|
for (const [how, reserved] of used) {
|
|
4593
4791
|
if (typeof reserved === "string" && reserved.startsWith(RESERVED_PARAMETER_PREFIX)) {
|
|
4594
|
-
problems.push(`parameter ${String(
|
|
4792
|
+
problems.push(`parameter ${String(name2)} ${how} ${reserved}: names starting with ${RESERVED_PARAMETER_PREFIX} are reserved by the app, which asks the user for the file server itself and never shows those values to a plugin`);
|
|
4595
4793
|
}
|
|
4596
4794
|
}
|
|
4597
4795
|
}
|
|
4598
4796
|
return problems;
|
|
4599
4797
|
}
|
|
4600
4798
|
|
|
4601
|
-
//
|
|
4799
|
+
// trial-runner/trial.ts
|
|
4602
4800
|
async function readFiles(path) {
|
|
4603
4801
|
const entries = path.endsWith(".zip") ? [...readZip(await readFile4(path))] : await (async () => {
|
|
4604
|
-
const locales = (await readdir3(join3(path, LOCALES)).catch(() => [])).filter((
|
|
4605
|
-
const names = [...(await readdir3(path)).filter((
|
|
4606
|
-
return Promise.all(names.map(async (
|
|
4802
|
+
const locales = (await readdir3(join3(path, LOCALES)).catch(() => [])).filter((name2) => name2.endsWith(".json")).map((name2) => `${LOCALES}/${name2}`);
|
|
4803
|
+
const names = [...(await readdir3(path)).filter((name2) => /\.m?js$/.test(name2) || name2 === "manifest.json"), ...locales];
|
|
4804
|
+
return Promise.all(names.map(async (name2) => [name2, await readFile4(join3(path, name2))]));
|
|
4607
4805
|
})();
|
|
4608
|
-
return new Map(entries.map(([
|
|
4609
|
-
if (!
|
|
4806
|
+
return new Map(entries.map(([name2, data]) => {
|
|
4807
|
+
if (!name2.endsWith(".json")) return [name2, Buffer.from(data).toString("utf8")];
|
|
4610
4808
|
const text = pluginJSONText(data);
|
|
4611
4809
|
if (text === void 0 || nestedTooDeep(text)) {
|
|
4612
|
-
throw new Error(`${
|
|
4810
|
+
throw new Error(`${name2} in ${path} must be UTF-8 JSON without a byte order mark or NUL, nested at most ${VALUE_LIMITS.depth} levels`);
|
|
4613
4811
|
}
|
|
4614
|
-
return [
|
|
4812
|
+
return [name2, text];
|
|
4615
4813
|
}));
|
|
4616
4814
|
}
|
|
4617
4815
|
var LOCALES = "locales";
|
|
4618
4816
|
function dictionariesIn(files2) {
|
|
4619
|
-
return Object.fromEntries([...files2].flatMap(([
|
|
4620
|
-
const match = /^locales\/([^/]+)\.json$/.exec(
|
|
4817
|
+
return Object.fromEntries([...files2].flatMap(([name2, text]) => {
|
|
4818
|
+
const match = /^locales\/([^/]+)\.json$/.exec(name2);
|
|
4621
4819
|
return match === null ? [] : [[match[1], JSON.parse(text)]];
|
|
4622
4820
|
}));
|
|
4623
4821
|
}
|
|
4624
4822
|
async function readPlugin(path) {
|
|
4625
4823
|
const files2 = await readFiles(path);
|
|
4626
|
-
const scripts = [...files2.keys()].filter((
|
|
4824
|
+
const scripts = [...files2.keys()].filter((name2) => /\.m?js$/.test(name2));
|
|
4627
4825
|
if (scripts.length !== 1) throw new Error(`${path} must contain exactly one bundled .js file, found ${scripts.length}`);
|
|
4628
4826
|
const manifest = JSON.parse(files2.get("manifest.json") ?? "{}");
|
|
4629
4827
|
const source = files2.get(scripts[0]);
|
|
@@ -4746,9 +4944,9 @@ async function runSlotCase(plugin2, testCase) {
|
|
|
4746
4944
|
}
|
|
4747
4945
|
function report(results, log) {
|
|
4748
4946
|
const counts = { passed: 0, skipped: 0, failed: 0 };
|
|
4749
|
-
for (const { name, outcome } of results) {
|
|
4947
|
+
for (const { name: name2, outcome } of results) {
|
|
4750
4948
|
counts[outcome.status] += 1;
|
|
4751
|
-
log(outcome.status === "passed" ? `PASS ${
|
|
4949
|
+
log(outcome.status === "passed" ? `PASS ${name2}` : `${outcome.status === "skipped" ? "SKIP" : "FAIL"} ${name2}
|
|
4752
4950
|
${outcome.reason}`);
|
|
4753
4951
|
}
|
|
4754
4952
|
log(`passed ${counts.passed} skipped ${counts.skipped} failed ${counts.failed}`);
|
|
@@ -4760,7 +4958,9 @@ async function runCommand(pluginDirectory, casesDirectory, log) {
|
|
|
4760
4958
|
for (const violation of plugin2.violations) log(`STATIC ${plugin2.file}:${violation}`);
|
|
4761
4959
|
const cases = await readCases(casesDirectory);
|
|
4762
4960
|
const results = [];
|
|
4763
|
-
for (const { name, data } of cases)
|
|
4961
|
+
for (const { name: name2, data, byteOrderMark } of cases) {
|
|
4962
|
+
results.push({ name: name2, outcome: byteOrderMark ? { status: "failed", reason: BYTE_ORDER_MARK_IN_CASE } : await runSlotCase(plugin2, data) });
|
|
4963
|
+
}
|
|
4764
4964
|
return report(results, log) && plugin2.violations.length === 0;
|
|
4765
4965
|
}
|
|
4766
4966
|
var RecordRefused = class extends Error {
|
|
@@ -4783,28 +4983,43 @@ async function recordCommand(pluginDirectory, { slot, call: callName, args, cred
|
|
|
4783
4983
|
return { output: toJSON(value) };
|
|
4784
4984
|
};
|
|
4785
4985
|
await settle(invokeSlot(plugin2, { slot, call: callName, args, parameters, appKeys, output: null }, recording.fetch, credentials));
|
|
4786
|
-
const
|
|
4986
|
+
const own = credentials === null ? [] : Object.values(credentials).filter((value) => typeof value === "string" && value !== "").map((value, index) => ({ value, fake: fakeValue(value, index) }));
|
|
4987
|
+
const redacted = credentials === null ? null : Object.fromEntries(Object.entries(credentials).map(([key, value]) => [key, typeof value === "string" ? withOwnValuesReplaced(value, own) : REDACTED]));
|
|
4988
|
+
const keptArgs = withOwnValuesReplaced(args, own);
|
|
4787
4989
|
const secret = new Set(plugin2.parameters.filter((parameter) => parameter.secret).map((parameter) => parameter.name));
|
|
4788
|
-
const kept = parameters === void 0 ? void 0 : Object.fromEntries(Object.entries(parameters).map(([
|
|
4789
|
-
const keptKeys = appKeys === void 0 ? void 0 : Object.fromEntries(Object.keys(appKeys).map((
|
|
4790
|
-
const exchanges =
|
|
4990
|
+
const kept = parameters === void 0 ? void 0 : Object.fromEntries(Object.entries(parameters).map(([name2, value]) => [name2, secret.has(name2) ? REDACTED : value]));
|
|
4991
|
+
const keptKeys = appKeys === void 0 ? void 0 : Object.fromEntries(Object.keys(appKeys).map((name2) => [name2, REDACTED]));
|
|
4992
|
+
const exchanges = withOwnValuesReplaced(
|
|
4993
|
+
withoutValues(recording.exchanges, Object.values(appKeys ?? {}).filter((key) => key !== "")),
|
|
4994
|
+
own
|
|
4995
|
+
);
|
|
4996
|
+
const unacceptable = [...recording.unacceptable, ...exchanges.flatMap(({ request }) => {
|
|
4997
|
+
const kind = bodyKind(bodyFromJSON(request.body));
|
|
4998
|
+
return kind.kind === "bad" ? [`${request.method} ${request.url}: ${kind.reason}`] : [];
|
|
4999
|
+
})];
|
|
5000
|
+
if (unacceptable.length > 0) throw new RecordRefused(`a request body cannot be replayed the same way on both runners, nothing was recorded:
|
|
5001
|
+
${unacceptable.join("\n ")}`);
|
|
4791
5002
|
const replay = replayFetch(exchanges);
|
|
4792
|
-
const outcome = await settle(invokeSlot(plugin2, { slot, call: callName, args, parameters: kept, appKeys: keptKeys, output: null }, replay.fetch, redacted));
|
|
5003
|
+
const outcome = await settle(invokeSlot(plugin2, { slot, call: callName, args: keptArgs, parameters: kept, appKeys: keptKeys, output: null }, replay.fetch, redacted));
|
|
4793
5004
|
const testCase = {
|
|
4794
5005
|
slot,
|
|
4795
5006
|
...callName === void 0 ? {} : { call: callName },
|
|
4796
|
-
args,
|
|
5007
|
+
args: keptArgs,
|
|
4797
5008
|
...redacted === null ? {} : { credentials: redacted },
|
|
4798
5009
|
...kept === void 0 ? {} : { parameters: kept },
|
|
4799
5010
|
...keptKeys === void 0 ? {} : { appKeys: keptKeys },
|
|
4800
5011
|
exchanges,
|
|
4801
5012
|
...outcome
|
|
4802
5013
|
};
|
|
5014
|
+
const left = leftoverValues(testCase, own);
|
|
5015
|
+
if (left.length > 0) throw new RecordRefused(`recorded case still holds ${left.length} credential value(s) after replacing them with fakes, nothing was recorded`);
|
|
4803
5016
|
const findings = scanValue(testCase);
|
|
4804
5017
|
if (findings.length > 0) throw new RecordRefused(`recorded case still holds credentials:
|
|
4805
5018
|
${findings.join("\n")}`);
|
|
4806
|
-
|
|
4807
|
-
|
|
5019
|
+
const text = `${JSON.stringify(testCase, null, 2)}
|
|
5020
|
+
`;
|
|
5021
|
+
if (holdsByteOrderMark(text)) throw new RecordRefused(`the plugin's arguments or output hold U+FEFF, nothing was recorded: ${BYTE_ORDER_MARK_IN_CASE}`);
|
|
5022
|
+
await writeFile(out, text);
|
|
4808
5023
|
return testCase;
|
|
4809
5024
|
}
|
|
4810
5025
|
function withoutValues(value, secrets) {
|
|
@@ -4817,6 +5032,89 @@ function withoutValues(value, secrets) {
|
|
|
4817
5032
|
};
|
|
4818
5033
|
return walk(value);
|
|
4819
5034
|
}
|
|
5035
|
+
var LAYERS = 5;
|
|
5036
|
+
function encodings(text) {
|
|
5037
|
+
const out = [text];
|
|
5038
|
+
for (let layer = 0; layer < LAYERS; layer += 1) out.push(encodeURIComponent(out[out.length - 1]));
|
|
5039
|
+
return out;
|
|
5040
|
+
}
|
|
5041
|
+
function occurrences(own) {
|
|
5042
|
+
const fakeOf = /* @__PURE__ */ new Map();
|
|
5043
|
+
for (const { value, fake } of own) {
|
|
5044
|
+
const values = encodings(value);
|
|
5045
|
+
const fakes = encodings(fake);
|
|
5046
|
+
values.forEach((encoded, layer) => {
|
|
5047
|
+
if (!fakeOf.has(encoded)) fakeOf.set(encoded, fakes[layer]);
|
|
5048
|
+
});
|
|
5049
|
+
}
|
|
5050
|
+
const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
5051
|
+
const afterEscape = "(?<=%(?:25)*[0-9A-Fa-f]{2})";
|
|
5052
|
+
const alternatives = [...fakeOf.keys()].sort((a, b) => b.length - a.length).map((text) => /^\d+$/.test(text) ? `(?:(?<!\\d)|${afterEscape})${escape(text)}(?!\\d)` : `(?:(?<![A-Za-z0-9])|${afterEscape})${escape(text)}(?![A-Za-z0-9])`);
|
|
5053
|
+
return { pattern: new RegExp(alternatives.join("|"), "g"), fakeOf };
|
|
5054
|
+
}
|
|
5055
|
+
var asBytes = (text) => Buffer.from(text, "utf8").toString("latin1");
|
|
5056
|
+
function decodedLayers(bytes2) {
|
|
5057
|
+
const layers = [bytes2];
|
|
5058
|
+
for (let layer = 0; layer < LAYERS; layer += 1) {
|
|
5059
|
+
const last = layers[layers.length - 1];
|
|
5060
|
+
const next = last.replace(/%([0-9A-Fa-f]{2})/g, (_, hex2) => String.fromCharCode(parseInt(hex2, 16)));
|
|
5061
|
+
if (next === last) break;
|
|
5062
|
+
layers.push(next);
|
|
5063
|
+
}
|
|
5064
|
+
return layers;
|
|
5065
|
+
}
|
|
5066
|
+
function bytePattern(own) {
|
|
5067
|
+
const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
5068
|
+
return new RegExp([...new Set(own.map(({ value }) => asBytes(value)))].sort((a, b) => b.length - a.length).map((text) => /^\d+$/.test(text) ? `(?<!\\d)${escape(text)}(?!\\d)` : `(?<![A-Za-z0-9])${escape(text)}(?![A-Za-z0-9])`).join("|"), "g");
|
|
5069
|
+
}
|
|
5070
|
+
function withOwnValuesReplaced(value, own) {
|
|
5071
|
+
if (own.length === 0) return value;
|
|
5072
|
+
const { pattern, fakeOf } = occurrences(own);
|
|
5073
|
+
const walk = (item) => {
|
|
5074
|
+
if (typeof item === "string") return item.replace(pattern, (found) => fakeOf.get(found) ?? found);
|
|
5075
|
+
if (typeof item === "number") {
|
|
5076
|
+
const fake = fakeOf.get(String(item));
|
|
5077
|
+
return fake !== void 0 && /^\d+$/.test(fake) ? Number(fake) : item;
|
|
5078
|
+
}
|
|
5079
|
+
if (Array.isArray(item)) return item.map(walk);
|
|
5080
|
+
if (item !== null && typeof item === "object") {
|
|
5081
|
+
if (typeof item.$bytes === "string") return item;
|
|
5082
|
+
return Object.fromEntries(Object.entries(item).map(([key, entry]) => [walk(key), walk(entry)]));
|
|
5083
|
+
}
|
|
5084
|
+
return item;
|
|
5085
|
+
};
|
|
5086
|
+
return walk(value);
|
|
5087
|
+
}
|
|
5088
|
+
function leftoverValues(testCase, own) {
|
|
5089
|
+
const checked = own.filter(({ value }) => value.length >= 3 && value !== REDACTED);
|
|
5090
|
+
if (checked.length === 0) return [];
|
|
5091
|
+
const pattern = bytePattern(checked);
|
|
5092
|
+
const values = new Set(checked.map(({ value }) => value));
|
|
5093
|
+
const found = [];
|
|
5094
|
+
const inLayers = (text) => {
|
|
5095
|
+
const layers = decodedLayers(text).map((layer) => layer.match(pattern) ?? []);
|
|
5096
|
+
found.push(...layers.reduce((most, matches) => matches.length > most.length ? matches : most, []));
|
|
5097
|
+
};
|
|
5098
|
+
const walk = (item) => {
|
|
5099
|
+
if (typeof item === "string") return inLayers(asBytes(item));
|
|
5100
|
+
if (typeof item === "number") {
|
|
5101
|
+
if (values.has(String(item))) found.push(String(item));
|
|
5102
|
+
return;
|
|
5103
|
+
}
|
|
5104
|
+
if (Array.isArray(item)) return item.forEach(walk);
|
|
5105
|
+
if (item === null || typeof item !== "object") return;
|
|
5106
|
+
const bytes2 = item.$bytes;
|
|
5107
|
+
if (typeof bytes2 === "string") {
|
|
5108
|
+
return inLayers(Buffer.from(bytes2, "base64").toString("latin1"));
|
|
5109
|
+
}
|
|
5110
|
+
for (const [key, entry] of Object.entries(item)) {
|
|
5111
|
+
walk(key);
|
|
5112
|
+
walk(entry);
|
|
5113
|
+
}
|
|
5114
|
+
};
|
|
5115
|
+
walk(testCase);
|
|
5116
|
+
return found;
|
|
5117
|
+
}
|
|
4820
5118
|
async function scanCommand(directories, log) {
|
|
4821
5119
|
const { files: files2, findings } = await scanDirectories(directories);
|
|
4822
5120
|
for (const finding of findings) log(`CREDENTIAL ${finding}`);
|
|
@@ -4833,7 +5131,7 @@ if (false) {
|
|
|
4833
5131
|
}
|
|
4834
5132
|
}
|
|
4835
5133
|
|
|
4836
|
-
//
|
|
5134
|
+
// trial-runner/sandbox.ts
|
|
4837
5135
|
import vm from "node:vm";
|
|
4838
5136
|
var UTF8_LABELS = /* @__PURE__ */ new Set(["unicode-1-1-utf-8", "unicode11utf8", "unicode20utf8", "utf-8", "utf8", "x-unicode20utf8"]);
|
|
4839
5137
|
var Utf8TextDecoder = class extends TextDecoder {
|
|
@@ -4856,8 +5154,8 @@ async function loadPlugin(source, { identifier, allowCodeGeneration }) {
|
|
|
4856
5154
|
const silent = () => {
|
|
4857
5155
|
};
|
|
4858
5156
|
const consoleObject = Object.freeze({ debug: silent, trace: silent, log: silent, info: silent, warn: silent, error: silent });
|
|
4859
|
-
for (const [
|
|
4860
|
-
Object.defineProperty(global,
|
|
5157
|
+
for (const [name2, value] of [["TextEncoder", TextEncoder], ["TextDecoder", Utf8TextDecoder], ["console", consoleObject]]) {
|
|
5158
|
+
Object.defineProperty(global, name2, { value, writable: true, configurable: true });
|
|
4861
5159
|
}
|
|
4862
5160
|
const module = new vm.SourceTextModule(source, { context, identifier });
|
|
4863
5161
|
await module.link(() => {
|
|
@@ -4867,7 +5165,7 @@ async function loadPlugin(source, { identifier, allowCodeGeneration }) {
|
|
|
4867
5165
|
return module.namespace;
|
|
4868
5166
|
}
|
|
4869
5167
|
|
|
4870
|
-
//
|
|
5168
|
+
// packer/pack.ts
|
|
4871
5169
|
var TEMPLATES = fileURLToPath2(new URL("../templates/", import.meta.url));
|
|
4872
5170
|
var SAMPLES = fileURLToPath2(new URL("../samples/src/", import.meta.url));
|
|
4873
5171
|
var SAMPLE_PACKAGES = fileURLToPath2(new URL("../samples/dist/", import.meta.url));
|
|
@@ -4929,51 +5227,51 @@ function inheritedFunctions(slot, functions) {
|
|
|
4929
5227
|
function capabilitiesOf(namespace) {
|
|
4930
5228
|
const problems = [];
|
|
4931
5229
|
const found = /* @__PURE__ */ new Set();
|
|
4932
|
-
for (const [
|
|
4933
|
-
const top = TOP_LEVEL_FUNCTIONS[
|
|
5230
|
+
for (const [name2, value] of Object.entries(namespace)) {
|
|
5231
|
+
const top = TOP_LEVEL_FUNCTIONS[name2];
|
|
4934
5232
|
if (top !== void 0) {
|
|
4935
5233
|
if (typeof value === "function") found.add(top);
|
|
4936
|
-
else problems.push(`${
|
|
5234
|
+
else problems.push(`${name2} must be a function`);
|
|
4937
5235
|
continue;
|
|
4938
5236
|
}
|
|
4939
|
-
const rule = SLOT_RULES[
|
|
5237
|
+
const rule = SLOT_RULES[name2];
|
|
4940
5238
|
if (rule === void 0) {
|
|
4941
|
-
problems.push(`exports ${
|
|
5239
|
+
problems.push(`exports ${name2}; plugins export only ${[...Object.keys(SLOT_RULES), ...Object.keys(TOP_LEVEL_FUNCTIONS)].join(", ")}`);
|
|
4942
5240
|
continue;
|
|
4943
5241
|
}
|
|
4944
5242
|
if (typeof value !== "object" || value === null) {
|
|
4945
|
-
problems.push(`${
|
|
5243
|
+
problems.push(`${name2} must be an object of functions`);
|
|
4946
5244
|
continue;
|
|
4947
5245
|
}
|
|
4948
5246
|
const has = (member) => typeof slotMember(value, member) === "function";
|
|
4949
5247
|
for (const member of Object.getOwnPropertyNames(value)) {
|
|
4950
|
-
if (!rule.functions.includes(member)) problems.push(`${
|
|
4951
|
-
else if (!has(member)) problems.push(`${
|
|
5248
|
+
if (!rule.functions.includes(member)) problems.push(`${name2}.${member} is not in the contract (${rule.functions.join(", ")})`);
|
|
5249
|
+
else if (!has(member)) problems.push(`${name2}.${member} must be a function`);
|
|
4952
5250
|
}
|
|
4953
5251
|
for (const member of inheritedFunctions(value, rule.functions)) {
|
|
4954
|
-
problems.push(`${
|
|
5252
|
+
problems.push(`${name2}.${member} is inherited; slot functions must be the object's own properties (an object literal, not a class instance)`);
|
|
4955
5253
|
}
|
|
4956
|
-
for (const member of rule.required) if (!has(member)) problems.push(`${
|
|
5254
|
+
for (const member of rule.required) if (!has(member)) problems.push(`${name2} needs ${member}`);
|
|
4957
5255
|
for (const [first, second] of rule.pairs) {
|
|
4958
5256
|
if (has(first) !== has(second)) {
|
|
4959
5257
|
const [present, missing] = has(first) ? [first, second] : [second, first];
|
|
4960
|
-
problems.push(`${
|
|
5258
|
+
problems.push(`${name2}.${present} needs ${name2}.${missing}`);
|
|
4961
5259
|
}
|
|
4962
5260
|
}
|
|
4963
5261
|
const generated = Object.entries(rule.capabilities).filter(([, any]) => any.some(has)).map(([capability]) => capability);
|
|
4964
5262
|
generated.forEach((capability) => found.add(capability));
|
|
4965
5263
|
const all = Object.values(rule.capabilities).flat();
|
|
4966
|
-
if (all.length > 0 && generated.length === 0) problems.push(`${
|
|
5264
|
+
if (all.length > 0 && generated.length === 0) problems.push(`${name2} needs one of ${all.join(", ")}`);
|
|
4967
5265
|
}
|
|
4968
5266
|
if (found.has("library") && found.has("resources")) {
|
|
4969
5267
|
problems.push("exports both library and resources; a source that lists all its content is scanned into the library, so it does not also answer find");
|
|
4970
5268
|
}
|
|
4971
|
-
return { capabilities: Capability.values.filter((
|
|
5269
|
+
return { capabilities: Capability.values.filter((name2) => found.has(name2)), problems };
|
|
4972
5270
|
}
|
|
4973
5271
|
function notYetUsedExports(namespace) {
|
|
4974
5272
|
const unused = new Set(NOT_YET_USED);
|
|
4975
|
-
const exported2 = Object.entries(namespace).flatMap(([
|
|
4976
|
-
return exported2.filter((
|
|
5273
|
+
const exported2 = Object.entries(namespace).flatMap(([name2, value]) => TOP_LEVEL_FUNCTIONS[name2] !== void 0 ? [name2] : (SLOT_RULES[name2]?.functions ?? []).filter((member) => typeof slotMember(value, member) === "function").map((member) => `${name2}.${member}`));
|
|
5274
|
+
return exported2.filter((name2) => unused.has(name2));
|
|
4977
5275
|
}
|
|
4978
5276
|
async function pack(directory, warn = () => {
|
|
4979
5277
|
}) {
|
|
@@ -4996,7 +5294,7 @@ async function pack(directory, warn = () => {
|
|
|
4996
5294
|
const { capabilities, problems } = capabilitiesOf(namespace);
|
|
4997
5295
|
if (capabilities.length === 0 && problems.length === 0) problems.push("exports no capability; a plugin exports at least one slot or resolve");
|
|
4998
5296
|
if (problems.length > 0) throw new Error(`${directory}: ${problems.join("; ")}`);
|
|
4999
|
-
for (const
|
|
5297
|
+
for (const name2 of notYetUsedExports(namespace)) warn(`WARN ${directory}: exports ${name2}, which this version of the App does not call yet (App \u5C1A\u672A\u4F7F\u7528)`);
|
|
5000
5298
|
const { default: metadata } = await import(pathToFileURL(join4(directory, "manifest.ts")).href);
|
|
5001
5299
|
if (metadata.interfaceLevel > CONTRACT.interfaceLevel || metadata.contractRevision !== CONTRACT.revision) {
|
|
5002
5300
|
throw new Error(`${directory}/manifest.ts targets interface level ${metadata.interfaceLevel} revision ${metadata.contractRevision}; the contract is level ${CONTRACT.interfaceLevel} revision ${CONTRACT.revision}`);
|
|
@@ -5033,7 +5331,7 @@ if (false) {
|
|
|
5033
5331
|
}
|
|
5034
5332
|
}
|
|
5035
5333
|
|
|
5036
|
-
//
|
|
5334
|
+
// package/cli.ts
|
|
5037
5335
|
var here2 = dirname2(fileURLToPath3(import.meta.url));
|
|
5038
5336
|
var ROOT = basename2(here2) === "dist" ? dirname2(here2) : here2;
|
|
5039
5337
|
var PACKAGED = basename2(here2) === "dist";
|
|
@@ -5066,8 +5364,8 @@ async function bundle(directory, out, log) {
|
|
|
5066
5364
|
function rewriteImports(source) {
|
|
5067
5365
|
return source.replace(/from "(?:\.\.\/)+contract\/contract\.ts"/g, `from "${PACKAGE_NAME}"`);
|
|
5068
5366
|
}
|
|
5069
|
-
var SCAFFOLD_PACKAGE = (
|
|
5070
|
-
name,
|
|
5367
|
+
var SCAFFOLD_PACKAGE = (name2, version) => ({
|
|
5368
|
+
name: name2,
|
|
5071
5369
|
private: true,
|
|
5072
5370
|
type: "module",
|
|
5073
5371
|
scripts: { check: `${PACKAGE_NAME} check`, bundle: `${PACKAGE_NAME} bundle`, trial: `${PACKAGE_NAME} trial` },
|
|
@@ -5090,7 +5388,7 @@ async function fallbackConfig(directory) {
|
|
|
5090
5388
|
await writeFile3(config, JSON.stringify({ compilerOptions: COMPILER_OPTIONS, files: ["plugin.ts", "manifest.ts"].map((file) => join5(directory, file)) }));
|
|
5091
5389
|
return config;
|
|
5092
5390
|
}
|
|
5093
|
-
async function newCommand(directory, { id, name, template = "apple-hls" }, log) {
|
|
5391
|
+
async function newCommand(directory, { id, name: name2, template = "apple-hls" }, log) {
|
|
5094
5392
|
const target = resolve3(directory);
|
|
5095
5393
|
if (existsSync(target) && (await readdir5(target)).length > 0) throw new UsageError(`${target} already exists and is not empty`);
|
|
5096
5394
|
const source = join5(TEMPLATES2, template);
|
|
@@ -5101,7 +5399,7 @@ async function newCommand(directory, { id, name, template = "apple-hls" }, log)
|
|
|
5101
5399
|
for (const file of ["plugin.ts", "manifest.ts"]) {
|
|
5102
5400
|
await writeFile3(join5(target, file), rewriteImports(await readFile6(join5(target, file), "utf8")));
|
|
5103
5401
|
}
|
|
5104
|
-
const manifest = (await readFile6(join5(target, "manifest.ts"), "utf8")).replace(/id: "[^"]*"/, () => `id: ${JSON.stringify(pluginId)}`).replace(/sourceId: "[^"]*"/, () => `sourceId: ${JSON.stringify(slug)}`).replace(/name: "[^"]*"/, () => `name: ${JSON.stringify(
|
|
5402
|
+
const manifest = (await readFile6(join5(target, "manifest.ts"), "utf8")).replace(/id: "[^"]*"/, () => `id: ${JSON.stringify(pluginId)}`).replace(/sourceId: "[^"]*"/, () => `sourceId: ${JSON.stringify(slug)}`).replace(/name: "[^"]*"/, () => `name: ${JSON.stringify(name2 ?? basename2(target))}`).replace(/author: "[^"]*"/, () => `author: "<your name>"`).replace(/version: "[^"]*"/, () => `version: "0.1.0"`);
|
|
5105
5403
|
await writeFile3(join5(target, "manifest.ts"), manifest);
|
|
5106
5404
|
const { version } = JSON.parse(await readFile6(join5(ROOT, "package.json"), "utf8"));
|
|
5107
5405
|
await writeFile3(join5(target, "package.json"), `${JSON.stringify(SCAFFOLD_PACKAGE(slug, version), null, 2)}
|