@tauri-cordis/manifest 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +2 -2
- package/package.json +38 -3
- package/src/index.d.mts +7 -0
- package/src/index.mjs +7 -0
- package/src/manifest.d.mts +93 -0
- package/src/manifest.mjs +206 -0
- package/src/names.d.mts +20 -0
- package/src/names.mjs +51 -0
- package/src/package.d.mts +60 -0
- package/src/package.mjs +166 -0
- package/src/schema.d.mts +1 -0
- package/src/schema.mjs +71 -0
- package/src/semver.d.mts +12 -0
- package/src/semver.mjs +116 -0
- package/src/signature.d.mts +68 -0
- package/src/signature.mjs +102 -0
- package/src/zip.d.mts +14 -0
- package/src/zip.mjs +152 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 TixXin
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@tauri-cordis/manifest`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Plugin manifest validation, deterministic zip packaging, and Ed25519 package signatures for [`tauri-cordis`](https://github.com/TixXin/tauri-cordis).
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tauri-cordis/manifest",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Plugin manifest validation, deterministic zip packaging, and Ed25519 package signatures for tauri-cordis",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/TixXin/tauri-cordis.git",
|
|
10
|
+
"directory": "packages/manifest"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/TixXin/tauri-cordis",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/TixXin/tauri-cordis/issues"
|
|
15
|
+
},
|
|
16
|
+
"publishConfig": {
|
|
17
|
+
"access": "public"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"src",
|
|
21
|
+
"README.md",
|
|
22
|
+
"LICENSE"
|
|
23
|
+
],
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./src/index.d.mts",
|
|
27
|
+
"default": "./src/index.mjs"
|
|
28
|
+
},
|
|
29
|
+
"./names": {
|
|
30
|
+
"types": "./src/names.d.mts",
|
|
31
|
+
"default": "./src/names.mjs"
|
|
32
|
+
},
|
|
33
|
+
"./package.json": "./package.json"
|
|
34
|
+
},
|
|
35
|
+
"engines": {
|
|
36
|
+
"node": ">=22.15"
|
|
37
|
+
},
|
|
38
|
+
"scripts": {
|
|
39
|
+
"test": "node --test \"test/**/*.test.mjs\""
|
|
40
|
+
}
|
|
6
41
|
}
|
package/src/index.d.mts
ADDED
package/src/index.mjs
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
export type LocalizedText = Record<string, string>;
|
|
2
|
+
|
|
3
|
+
export interface PluginCommand {
|
|
4
|
+
id: string;
|
|
5
|
+
title: LocalizedText;
|
|
6
|
+
keybinding?: string;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface PluginScreenshot {
|
|
10
|
+
path: string;
|
|
11
|
+
caption?: LocalizedText;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface AppManifest {
|
|
15
|
+
manifest: 1;
|
|
16
|
+
displayName: LocalizedText;
|
|
17
|
+
description: LocalizedText;
|
|
18
|
+
icon: string;
|
|
19
|
+
categories: string[];
|
|
20
|
+
screenshots?: PluginScreenshot[];
|
|
21
|
+
preview?: boolean;
|
|
22
|
+
platforms?: Array<"windows" | "macos" | "linux">;
|
|
23
|
+
host?: string;
|
|
24
|
+
client?: Record<string, string>;
|
|
25
|
+
inject?: { required?: string[]; optional?: string[] };
|
|
26
|
+
requires?: Record<string, string>;
|
|
27
|
+
provides?: string[];
|
|
28
|
+
replaces?: string[];
|
|
29
|
+
slots?: string[];
|
|
30
|
+
commands?: PluginCommand[];
|
|
31
|
+
network?: string[];
|
|
32
|
+
config?: string;
|
|
33
|
+
experimental?: string[];
|
|
34
|
+
nodeApis?: string[];
|
|
35
|
+
builtWith?: string;
|
|
36
|
+
[unknown: string]: unknown;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface PluginManifest {
|
|
40
|
+
name: string;
|
|
41
|
+
version: string;
|
|
42
|
+
type: "module";
|
|
43
|
+
description?: string;
|
|
44
|
+
author?: string | { name: string; email?: string; url?: string };
|
|
45
|
+
license: string;
|
|
46
|
+
homepage?: string;
|
|
47
|
+
repository: string | { type?: string; url: string; directory?: string };
|
|
48
|
+
bugs?: string | { url?: string; email?: string };
|
|
49
|
+
funding?: string | { type?: string; url: string } | Array<string | { type?: string; url: string }>;
|
|
50
|
+
keywords?: string[];
|
|
51
|
+
files?: string[];
|
|
52
|
+
engines: Record<string, string>;
|
|
53
|
+
[key: string]: unknown;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface ValidateManifestOptions {
|
|
57
|
+
appKey?: string;
|
|
58
|
+
officialScope?: string;
|
|
59
|
+
official?: boolean;
|
|
60
|
+
stage?: "source" | "built";
|
|
61
|
+
appVersion?: string;
|
|
62
|
+
allowExperimental?: boolean;
|
|
63
|
+
categories?: readonly string[];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface ManifestIssue {
|
|
67
|
+
path: string;
|
|
68
|
+
code: string;
|
|
69
|
+
message: string;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface ValidateManifestResult {
|
|
73
|
+
ok: boolean;
|
|
74
|
+
errors: ManifestIssue[];
|
|
75
|
+
warnings: ManifestIssue[];
|
|
76
|
+
manifest: PluginManifest | null;
|
|
77
|
+
app: AppManifest | null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export declare const DEFAULT_APP_KEY: "fuyu";
|
|
81
|
+
export declare const DEFAULT_OFFICIAL_SCOPE: "fuyu";
|
|
82
|
+
export declare const MANIFEST_VERSION: 1;
|
|
83
|
+
export declare const REQUIRED_LOCALES: readonly string[];
|
|
84
|
+
export declare const DEFAULT_CATEGORIES: readonly string[];
|
|
85
|
+
export declare const PLATFORMS: readonly ["windows", "macos", "linux"];
|
|
86
|
+
export declare const MAX_SCREENSHOTS: number;
|
|
87
|
+
export declare const GENERATED_FIELDS: readonly ["nodeApis", "builtWith"];
|
|
88
|
+
export declare const NPM_FIELDS: readonly string[];
|
|
89
|
+
export declare const APP_FIELDS: readonly string[];
|
|
90
|
+
|
|
91
|
+
export declare function isSafeRelativePath(path: unknown): boolean;
|
|
92
|
+
|
|
93
|
+
export declare function validateManifest(pkg: unknown, options?: ValidateManifestOptions): ValidateManifestResult;
|
package/src/manifest.mjs
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { checkPluginName, parseRepository } from "./names.mjs";
|
|
2
|
+
import { isValidRange, isValidVersion, satisfies } from "./semver.mjs";
|
|
3
|
+
|
|
4
|
+
export const DEFAULT_APP_KEY = "fuyu";
|
|
5
|
+
export const DEFAULT_OFFICIAL_SCOPE = "fuyu";
|
|
6
|
+
export const MANIFEST_VERSION = 1;
|
|
7
|
+
export const REQUIRED_LOCALES = ["zh-CN", "en"];
|
|
8
|
+
export const DEFAULT_CATEGORIES = ["productivity", "todos", "developer", "media", "messages", "information", "utilities"];
|
|
9
|
+
export const PLATFORMS = ["windows", "macos", "linux"];
|
|
10
|
+
export const MAX_SCREENSHOTS = 6;
|
|
11
|
+
export const GENERATED_FIELDS = ["nodeApis", "builtWith"];
|
|
12
|
+
|
|
13
|
+
export const NPM_FIELDS = [
|
|
14
|
+
"name", "version", "type", "description", "author", "contributors", "maintainers", "license", "homepage", "repository", "bugs",
|
|
15
|
+
"funding", "keywords", "files", "engines", "private", "main", "module", "exports", "imports", "types", "typings", "scripts",
|
|
16
|
+
"dependencies", "devDependencies", "peerDependencies", "peerDependenciesMeta", "optionalDependencies", "bundleDependencies",
|
|
17
|
+
"bundledDependencies", "overrides", "packageManager", "publishConfig", "sideEffects", "workspaces", "os", "cpu", "browser",
|
|
18
|
+
"directories", "man", "bin", "config", "$schema",
|
|
19
|
+
];
|
|
20
|
+
|
|
21
|
+
export const APP_FIELDS = [
|
|
22
|
+
"manifest", "displayName", "description", "icon", "categories", "screenshots", "preview", "platforms", "host", "client", "inject",
|
|
23
|
+
"requires", "provides", "replaces", "slots", "commands", "network", "config", "experimental", "nodeApis", "builtWith",
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
27
|
+
const isText = (value) => typeof value === "string" && value.trim() !== "";
|
|
28
|
+
const HOSTNAME = /^(?:\*\.)?(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,62}$|^localhost$/;
|
|
29
|
+
const SPEC = /^[A-Za-z0-9@][A-Za-z0-9@._/:-]*$/;
|
|
30
|
+
|
|
31
|
+
export function isSafeRelativePath(path) {
|
|
32
|
+
if (!isText(path) || path.includes("\\") || path.includes("\0") || path.startsWith("/") || /^[A-Za-z]:/.test(path)) return false;
|
|
33
|
+
return path.split("/").every((part) => part !== "" && part !== "." && part !== "..");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function createChecker() {
|
|
37
|
+
const errors = [];
|
|
38
|
+
const warnings = [];
|
|
39
|
+
const error = (path, code, message) => errors.push({ path, code, message });
|
|
40
|
+
const warn = (path, code, message) => warnings.push({ path, code, message });
|
|
41
|
+
const unknown = (object, known, prefix) => {
|
|
42
|
+
for (const key of Object.keys(object)) if (!known.includes(key)) warn(`${prefix}${key}`, "unknown", `${prefix}${key} is not a known field and is ignored`);
|
|
43
|
+
};
|
|
44
|
+
const localized = (value, path, required) => {
|
|
45
|
+
if (value === undefined) {
|
|
46
|
+
if (required) error(path, "required", `${path} is required`);
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
if (!isObject(value)) return error(path, "localized", `${path} must map languages to text, e.g. { "zh-CN": "…", "en": "…" }`);
|
|
50
|
+
for (const locale of REQUIRED_LOCALES) if (!isText(value[locale])) error(`${path}.${locale}`, "required", `${path} needs "${locale}" text`);
|
|
51
|
+
for (const [locale, text] of Object.entries(value)) if (typeof text !== "string") error(`${path}.${locale}`, "type", `${path}.${locale} must be text`);
|
|
52
|
+
};
|
|
53
|
+
const strings = (value, path, test = isText, what = "non-empty text") => {
|
|
54
|
+
if (value === undefined) return;
|
|
55
|
+
if (!Array.isArray(value)) return error(path, "type", `${path} must be a list`);
|
|
56
|
+
value.forEach((item, index) => {
|
|
57
|
+
if (!test(item)) error(`${path}[${index}]`, "type", `${path}[${index}] must be ${what}`);
|
|
58
|
+
});
|
|
59
|
+
const seen = new Set();
|
|
60
|
+
for (const item of value) {
|
|
61
|
+
if (seen.has(item)) warn(path, "duplicate", `${path} lists "${item}" more than once`);
|
|
62
|
+
seen.add(item);
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
const file = (value, path, required, extensions) => {
|
|
66
|
+
if (value === undefined) {
|
|
67
|
+
if (required) error(path, "required", `${path} is required`);
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (!isSafeRelativePath(value)) return error(path, "path", `${path} must be a relative path inside the package, with "/" and no ".."`);
|
|
71
|
+
if (extensions && !extensions.some((extension) => value.toLowerCase().endsWith(extension))) {
|
|
72
|
+
error(path, "path", `${path} must end with ${extensions.join(" or ")}`);
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
return { errors, warnings, error, warn, unknown, localized, strings, file };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function checkPackage(pkg, check, options) {
|
|
79
|
+
const { error, unknown, strings } = check;
|
|
80
|
+
const appKey = options.appKey;
|
|
81
|
+
if (!isText(pkg.name)) error("name", "required", "name is required");
|
|
82
|
+
else {
|
|
83
|
+
const problem = checkPluginName(pkg.name, pkg.repository, options);
|
|
84
|
+
if (problem) error("name", problem.code, problem.message);
|
|
85
|
+
}
|
|
86
|
+
if (!isText(pkg.version)) error("version", "required", "version is required");
|
|
87
|
+
else if (!isValidVersion(pkg.version) || pkg.version.startsWith("v")) error("version", "semver", `version "${pkg.version}" is not semver (e.g. 1.2.0)`);
|
|
88
|
+
if (pkg.type !== "module") error("type", "module", 'type must be "module"');
|
|
89
|
+
if (!isText(pkg.license)) error("license", "required", "license is required (an SPDX id such as MIT)");
|
|
90
|
+
else if (pkg.license.trim().toUpperCase() === "UNLICENSED") error("license", "license", "plugins must be open source: UNLICENSED is not accepted");
|
|
91
|
+
if (pkg.repository === undefined) error("repository", "required", 'repository is required (e.g. "github:owner/name")');
|
|
92
|
+
else if (!parseRepository(pkg.repository)) error("repository", "repository", "repository must name a source repository, e.g. github:owner/name");
|
|
93
|
+
if (!isObject(pkg.engines) || pkg.engines[appKey] === undefined) error(`engines.${appKey}`, "required", `engines.${appKey} is required`);
|
|
94
|
+
else if (!isText(pkg.engines[appKey]) || !isValidRange(pkg.engines[appKey])) {
|
|
95
|
+
error(`engines.${appKey}`, "range", `engines.${appKey} must be a semver range such as ">=0.4.0"`);
|
|
96
|
+
} else if (options.appVersion !== undefined && !satisfies(options.appVersion, pkg.engines[appKey])) {
|
|
97
|
+
error(`engines.${appKey}`, "engine", `needs ${appKey} ${pkg.engines[appKey]}, this is ${options.appVersion}`);
|
|
98
|
+
}
|
|
99
|
+
if (pkg.description !== undefined && typeof pkg.description !== "string") error("description", "type", "description must be text");
|
|
100
|
+
if (pkg.homepage !== undefined && !isText(pkg.homepage)) error("homepage", "type", "homepage must be a URL");
|
|
101
|
+
strings(pkg.keywords, "keywords");
|
|
102
|
+
strings(pkg.files, "files");
|
|
103
|
+
unknown(pkg, [...NPM_FIELDS, appKey], "");
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function checkRequires(value, check) {
|
|
107
|
+
if (value === undefined) return;
|
|
108
|
+
if (!isObject(value)) return check.error("requires", "type", "requires must map plugin names to version ranges");
|
|
109
|
+
for (const [name, range] of Object.entries(value)) {
|
|
110
|
+
if (!/^@[^/]+\/[^/]+$/.test(name)) check.error(`requires.${name}`, "name", `requires.${name}: plugins are named @scope/name`);
|
|
111
|
+
if (!isText(range) || !isValidRange(range)) check.error(`requires.${name}`, "range", `requires.${name} must be a semver range`);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function checkCommands(value, path, check) {
|
|
116
|
+
if (value === undefined) return;
|
|
117
|
+
if (!Array.isArray(value)) return check.error(path, "type", `${path} must be a list`);
|
|
118
|
+
const ids = new Set();
|
|
119
|
+
value.forEach((command, index) => {
|
|
120
|
+
const at = `${path}[${index}]`;
|
|
121
|
+
if (!isObject(command)) return check.error(at, "type", `${at} must be an object`);
|
|
122
|
+
if (!isText(command.id)) check.error(`${at}.id`, "required", `${at}.id is required`);
|
|
123
|
+
else if (ids.has(command.id)) check.error(`${at}.id`, "duplicate", `command id "${command.id}" is used twice`);
|
|
124
|
+
ids.add(command.id);
|
|
125
|
+
check.localized(command.title, `${at}.title`, true);
|
|
126
|
+
if (command.keybinding !== undefined && !isText(command.keybinding)) check.error(`${at}.keybinding`, "type", `${at}.keybinding must be text`);
|
|
127
|
+
check.unknown(command, ["id", "title", "keybinding"], `${at}.`);
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function checkScreenshots(value, path, check) {
|
|
132
|
+
if (value === undefined) return;
|
|
133
|
+
if (!Array.isArray(value)) return check.error(path, "type", `${path} must be a list`);
|
|
134
|
+
if (value.length > MAX_SCREENSHOTS) check.error(path, "too-many", `at most ${MAX_SCREENSHOTS} screenshots`);
|
|
135
|
+
value.forEach((shot, index) => {
|
|
136
|
+
const at = `${path}[${index}]`;
|
|
137
|
+
if (!isObject(shot)) return check.error(at, "type", `${at} must be an object`);
|
|
138
|
+
check.file(shot.path, `${at}.path`, true, [".png", ".jpg", ".jpeg", ".webp"]);
|
|
139
|
+
check.localized(shot.caption, `${at}.caption`, false);
|
|
140
|
+
check.unknown(shot, ["path", "caption"], `${at}.`);
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function checkApp(app, check, options) {
|
|
145
|
+
const { error, warn, strings, file, localized } = check;
|
|
146
|
+
const p = `${options.appKey}.`;
|
|
147
|
+
if (app.manifest !== MANIFEST_VERSION) error(`${p}manifest`, "manifest", `${p}manifest must be ${MANIFEST_VERSION}`);
|
|
148
|
+
localized(app.displayName, `${p}displayName`, true);
|
|
149
|
+
localized(app.description, `${p}description`, true);
|
|
150
|
+
file(app.icon, `${p}icon`, true, [".png", ".svg"]);
|
|
151
|
+
if (!Array.isArray(app.categories) || app.categories.length === 0) error(`${p}categories`, "required", `${p}categories needs at least one category`);
|
|
152
|
+
else strings(app.categories, `${p}categories`, (item) => options.categories.includes(item), `one of ${options.categories.join(", ")}`);
|
|
153
|
+
checkScreenshots(app.screenshots, `${p}screenshots`, check);
|
|
154
|
+
if (app.preview !== undefined && typeof app.preview !== "boolean") error(`${p}preview`, "type", `${p}preview must be true or false`);
|
|
155
|
+
strings(app.platforms, `${p}platforms`, (item) => PLATFORMS.includes(item), `one of ${PLATFORMS.join(", ")}`);
|
|
156
|
+
file(app.host, `${p}host`, false, [".js", ".mjs"]);
|
|
157
|
+
if (app.client !== undefined) {
|
|
158
|
+
if (!isObject(app.client)) error(`${p}client`, "type", `${p}client must map window names to entry files`);
|
|
159
|
+
else for (const [window, entry] of Object.entries(app.client)) file(entry, `${p}client.${window}`, true, [".js", ".mjs"]);
|
|
160
|
+
}
|
|
161
|
+
if (app.inject !== undefined) {
|
|
162
|
+
if (!isObject(app.inject)) error(`${p}inject`, "type", `${p}inject must be { required, optional }`);
|
|
163
|
+
else {
|
|
164
|
+
strings(app.inject.required, `${p}inject.required`);
|
|
165
|
+
strings(app.inject.optional, `${p}inject.optional`);
|
|
166
|
+
check.unknown(app.inject, ["required", "optional"], `${p}inject.`);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
checkRequires(app.requires, check);
|
|
170
|
+
for (const key of ["provides", "replaces", "slots", "experimental"]) strings(app[key], `${p}${key}`);
|
|
171
|
+
strings(app.network, `${p}network`, (item) => typeof item === "string" && HOSTNAME.test(item), "a lowercase host name such as api.example.com");
|
|
172
|
+
checkCommands(app.commands, `${p}commands`, check);
|
|
173
|
+
file(app.config, `${p}config`, false, [".json"]);
|
|
174
|
+
if (Array.isArray(app.experimental) && app.experimental.length > 0 && !options.allowExperimental) {
|
|
175
|
+
error(`${p}experimental`, "experimental", "plugins that use experimental interfaces only load in development mode or as built-in plugins");
|
|
176
|
+
}
|
|
177
|
+
strings(app.nodeApis, `${p}nodeApis`, (item) => typeof item === "string" && SPEC.test(item), "a Node module name");
|
|
178
|
+
if (app.builtWith !== undefined && !isValidVersion(app.builtWith)) error(`${p}builtWith`, "semver", `${p}builtWith must be a version`);
|
|
179
|
+
if (options.stage === "source") {
|
|
180
|
+
for (const key of GENERATED_FIELDS) if (app[key] !== undefined) warn(`${p}${key}`, "generated", `${p}${key} is written by the build; the value here is replaced`);
|
|
181
|
+
}
|
|
182
|
+
check.unknown(app, APP_FIELDS, p);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export function validateManifest(pkg, options = {}) {
|
|
186
|
+
const resolved = {
|
|
187
|
+
appKey: options.appKey ?? DEFAULT_APP_KEY,
|
|
188
|
+
officialScope: options.officialScope ?? DEFAULT_OFFICIAL_SCOPE,
|
|
189
|
+
official: options.official ?? false,
|
|
190
|
+
stage: options.stage ?? "built",
|
|
191
|
+
appVersion: options.appVersion,
|
|
192
|
+
allowExperimental: options.allowExperimental ?? true,
|
|
193
|
+
categories: options.categories ?? DEFAULT_CATEGORIES,
|
|
194
|
+
};
|
|
195
|
+
const check = createChecker();
|
|
196
|
+
if (!isObject(pkg)) {
|
|
197
|
+
check.error("", "type", "package.json must be a JSON object");
|
|
198
|
+
return { ok: false, errors: check.errors, warnings: check.warnings, manifest: null, app: null };
|
|
199
|
+
}
|
|
200
|
+
checkPackage(pkg, check, resolved);
|
|
201
|
+
const app = pkg[resolved.appKey];
|
|
202
|
+
if (!isObject(app)) check.error(resolved.appKey, "required", `${resolved.appKey} is required`);
|
|
203
|
+
else checkApp(app, check, resolved);
|
|
204
|
+
const ok = check.errors.length === 0;
|
|
205
|
+
return { ok, errors: check.errors, warnings: check.warnings, manifest: ok ? pkg : null, app: ok ? app : null };
|
|
206
|
+
}
|
package/src/names.d.mts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export declare const SERVICE_NAME: RegExp;
|
|
2
|
+
|
|
3
|
+
export interface PluginName {
|
|
4
|
+
scope: string | null;
|
|
5
|
+
name: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface RepositoryRef {
|
|
9
|
+
host: string;
|
|
10
|
+
owner: string;
|
|
11
|
+
repo: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export declare function parsePluginName(name: unknown): PluginName | null;
|
|
15
|
+
export declare function parseRepository(repository: unknown): RepositoryRef | null;
|
|
16
|
+
export declare function checkPluginName(
|
|
17
|
+
name: string,
|
|
18
|
+
repository: unknown,
|
|
19
|
+
options?: { officialScope?: string; official?: boolean },
|
|
20
|
+
): { code: string; message: string } | null;
|
package/src/names.mjs
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
export const SERVICE_NAME = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*)*\/v[1-9][0-9]{0,3}$/;
|
|
2
|
+
|
|
3
|
+
const PART = /^[a-z0-9][a-z0-9._~-]*$/;
|
|
4
|
+
const OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/;
|
|
5
|
+
const SHORTHAND = /^(?:(github|gitlab|bitbucket):)?([^/:@\s]+)\/([^/\s#]+?)(?:\.git)?(?:#.*)?$/;
|
|
6
|
+
const HOSTS = { github: "github.com", gitlab: "gitlab.com", bitbucket: "bitbucket.org" };
|
|
7
|
+
|
|
8
|
+
export function parsePluginName(name) {
|
|
9
|
+
if (typeof name !== "string" || name.length > 214) return null;
|
|
10
|
+
const match = /^@([^/]+)\/([^/]+)$/.exec(name);
|
|
11
|
+
if (!match) return PART.test(name) ? { scope: null, name } : null;
|
|
12
|
+
return PART.test(match[1]) && PART.test(match[2]) ? { scope: match[1], name: match[2] } : null;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function parseRepository(repository) {
|
|
16
|
+
const text = typeof repository === "string" ? repository : repository && typeof repository === "object" ? repository.url : null;
|
|
17
|
+
if (typeof text !== "string" || text.trim() === "") return null;
|
|
18
|
+
const value = text.trim();
|
|
19
|
+
const short = SHORTHAND.exec(value);
|
|
20
|
+
if (short && !value.includes("://")) {
|
|
21
|
+
return OWNER.test(short[2]) ? { host: HOSTS[short[1] ?? "github"], owner: short[2], repo: short[3] } : null;
|
|
22
|
+
}
|
|
23
|
+
const scp = /^git@([^:]+):([^/]+)\/(.+?)(?:\.git)?\/?$/.exec(value);
|
|
24
|
+
if (scp) return OWNER.test(scp[2]) ? { host: scp[1].toLowerCase(), owner: scp[2], repo: scp[3] } : null;
|
|
25
|
+
let url;
|
|
26
|
+
try {
|
|
27
|
+
url = new URL(value.replace(/^git\+/, ""));
|
|
28
|
+
} catch {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
if (!["https:", "http:", "git:", "ssh:"].includes(url.protocol)) return null;
|
|
32
|
+
const [owner, repo] = url.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/, "").split("/");
|
|
33
|
+
if (!owner || !repo || !OWNER.test(owner)) return null;
|
|
34
|
+
return { host: url.hostname.toLowerCase(), owner, repo };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function checkPluginName(name, repository, { officialScope = "fuyu", official = false } = {}) {
|
|
38
|
+
const parsed = parsePluginName(name);
|
|
39
|
+
if (!parsed) return { code: "name", message: `"${name}" is not a valid package name: lowercase letters, digits, "-", "." and "_", optionally scoped` };
|
|
40
|
+
if (!parsed.scope) return { code: "name-unscoped", message: `"${name}" has no scope: name it @<repository owner>/${parsed.name}` };
|
|
41
|
+
const scope = parsed.scope.toLowerCase();
|
|
42
|
+
if (scope === officialScope.toLowerCase()) {
|
|
43
|
+
return official ? null : { code: "name-reserved", message: `@${officialScope}/* is reserved for official plugins` };
|
|
44
|
+
}
|
|
45
|
+
const repo = parseRepository(repository);
|
|
46
|
+
if (!repo) return null;
|
|
47
|
+
if (repo.owner.toLowerCase() !== scope) {
|
|
48
|
+
return { code: "name-owner", message: `the scope @${parsed.scope} must be the repository owner (${repo.owner})` };
|
|
49
|
+
}
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { PluginManifest } from "./manifest.mjs";
|
|
2
|
+
import type { PackageEntry } from "./zip.mjs";
|
|
3
|
+
|
|
4
|
+
export { PackageError } from "./zip.mjs";
|
|
5
|
+
export type { PackageEntry } from "./zip.mjs";
|
|
6
|
+
|
|
7
|
+
export interface PackageOptions {
|
|
8
|
+
namespace?: string;
|
|
9
|
+
extension?: string;
|
|
10
|
+
signatureFile?: string;
|
|
11
|
+
maxPackageBytes?: number;
|
|
12
|
+
maxUnpackedBytes?: number;
|
|
13
|
+
maxFiles?: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface ResolvedPackageOptions {
|
|
17
|
+
namespace: string;
|
|
18
|
+
extension: string;
|
|
19
|
+
signatureFile: string;
|
|
20
|
+
maxPackageBytes: number;
|
|
21
|
+
maxUnpackedBytes: number;
|
|
22
|
+
maxFiles: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface PackedPackage {
|
|
26
|
+
zip: Uint8Array;
|
|
27
|
+
digest: string;
|
|
28
|
+
manifest: PluginManifest;
|
|
29
|
+
files: PackageEntry[];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface ReadPackageResult {
|
|
33
|
+
files: PackageEntry[];
|
|
34
|
+
manifest: PluginManifest;
|
|
35
|
+
digest: string;
|
|
36
|
+
signatures: unknown;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export declare const DEFAULT_NAMESPACE: "fuyu";
|
|
40
|
+
export declare const MAX_PACKAGE_BYTES: number;
|
|
41
|
+
export declare const MAX_UNPACKED_BYTES: number;
|
|
42
|
+
export declare const MAX_FILES: number;
|
|
43
|
+
export declare const MANIFEST_FILE: "package.json";
|
|
44
|
+
export declare const TEXT_EXTENSIONS: readonly string[];
|
|
45
|
+
export declare const BLOCKED_EXTENSIONS: readonly string[];
|
|
46
|
+
|
|
47
|
+
export declare function resolvePackageOptions(options?: PackageOptions): ResolvedPackageOptions;
|
|
48
|
+
export declare function checkPackagePath(path: unknown): { code: string; message: string } | null;
|
|
49
|
+
export declare function executableKind(data: Uint8Array): "PE" | "Mach-O" | "ELF" | "WebAssembly" | "Java class" | "Java archive" | null;
|
|
50
|
+
export declare function normalizeText(path: string, data: Uint8Array): Uint8Array;
|
|
51
|
+
export declare function sha256Hex(data: Uint8Array | string): string;
|
|
52
|
+
export declare function packageDigest(entries: readonly PackageEntry[], options?: PackageOptions): string;
|
|
53
|
+
export declare function packFiles(
|
|
54
|
+
files: ReadonlyArray<{ path: string; data: Uint8Array | string }>,
|
|
55
|
+
options?: PackageOptions & { normalizeText?: boolean },
|
|
56
|
+
): PackedPackage;
|
|
57
|
+
export declare function collectFiles(dir: string): PackageEntry[];
|
|
58
|
+
export declare function packDirectory(dir: string, options?: PackageOptions): PackedPackage;
|
|
59
|
+
export declare function readPackage(zip: Uint8Array, options?: PackageOptions): ReadPackageResult;
|
|
60
|
+
export declare function packageFileName(name: string, version: string, options?: PackageOptions): string;
|
package/src/package.mjs
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { lstatSync, readFileSync, readdirSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { isSafeRelativePath } from "./manifest.mjs";
|
|
5
|
+
import { PackageError, createZip, readZip, zipEntryNames } from "./zip.mjs";
|
|
6
|
+
|
|
7
|
+
export { PackageError } from "./zip.mjs";
|
|
8
|
+
|
|
9
|
+
export const DEFAULT_NAMESPACE = "fuyu";
|
|
10
|
+
export const MAX_PACKAGE_BYTES = 20 * 1024 * 1024;
|
|
11
|
+
export const MAX_UNPACKED_BYTES = 100 * 1024 * 1024;
|
|
12
|
+
export const MAX_FILES = 5000;
|
|
13
|
+
export const MANIFEST_FILE = "package.json";
|
|
14
|
+
export const TEXT_EXTENSIONS = [".js", ".mjs", ".cjs", ".json", ".css", ".html", ".htm", ".md", ".txt", ".svg", ".map", ".yml", ".yaml", ".xml", ".csv"];
|
|
15
|
+
export const BLOCKED_EXTENSIONS = [".node", ".exe", ".dll", ".sys", ".scr", ".com", ".msi", ".so", ".dylib", ".bin", ".elf", ".app", ".appimage", ".deb", ".rpm", ".pkg", ".dmg", ".wasm", ".jar", ".class"];
|
|
16
|
+
|
|
17
|
+
const extensionOf = (path) => {
|
|
18
|
+
const base = path.slice(path.lastIndexOf("/") + 1).toLowerCase();
|
|
19
|
+
const dot = base.lastIndexOf(".");
|
|
20
|
+
return dot > 0 ? base.slice(dot) : "";
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export function resolvePackageOptions(options = {}) {
|
|
24
|
+
const namespace = options.namespace ?? DEFAULT_NAMESPACE;
|
|
25
|
+
return {
|
|
26
|
+
namespace,
|
|
27
|
+
extension: options.extension ?? `.${namespace}`,
|
|
28
|
+
signatureFile: options.signatureFile ?? `${namespace}-signature.json`,
|
|
29
|
+
maxPackageBytes: options.maxPackageBytes ?? MAX_PACKAGE_BYTES,
|
|
30
|
+
maxUnpackedBytes: options.maxUnpackedBytes ?? MAX_UNPACKED_BYTES,
|
|
31
|
+
maxFiles: options.maxFiles ?? MAX_FILES,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function checkPackagePath(path) {
|
|
36
|
+
if (typeof path !== "string" || !isSafeRelativePath(path)) return { code: "path", message: "must be a relative path with \"/\", no \"..\" and not absolute" };
|
|
37
|
+
if (/[\u0000-\u001f\u007f]/.test(path)) return { code: "path", message: "contains control characters" };
|
|
38
|
+
if (path.split("/").some((part) => part.toLowerCase() === "node_modules")) return { code: "node-modules", message: "node_modules is not allowed: bundle dependencies into dist/" };
|
|
39
|
+
const extension = extensionOf(path);
|
|
40
|
+
if (extension === ".node") return { code: "native", message: "native Node addons (.node) are not allowed" };
|
|
41
|
+
if (BLOCKED_EXTENSIONS.includes(extension)) return { code: "executable", message: `${extension} files are not allowed` };
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const MACHO = new Set([0xfeedface, 0xfeedfacf, 0xcefaedfe, 0xcffaedfe, 0xbebafeca, 0xcafebabf, 0xbfbafeca]);
|
|
46
|
+
const isJarEntry = (name) => name === "META-INF/MANIFEST.MF" || name.toLowerCase().endsWith(".class");
|
|
47
|
+
|
|
48
|
+
export function executableKind(data) {
|
|
49
|
+
if (data.length >= 2 && data[0] === 0x4d && data[1] === 0x5a) return "PE";
|
|
50
|
+
if (data.length < 4) return null;
|
|
51
|
+
const magic = data.readUInt32BE(0);
|
|
52
|
+
if (magic === 0x7f454c46) return "ELF";
|
|
53
|
+
if (magic === 0xcafebabe) return data.length >= 8 && data.readUInt32BE(4) >= 45 ? "Java class" : "Mach-O";
|
|
54
|
+
if (MACHO.has(magic)) return "Mach-O";
|
|
55
|
+
if (magic === 0x0061736d) return "WebAssembly";
|
|
56
|
+
if (magic === 0x504b0304 && zipEntryNames(data).some(isJarEntry)) return "Java archive";
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const strictUtf8 = new TextDecoder("utf-8", { fatal: true });
|
|
61
|
+
|
|
62
|
+
export function normalizeText(path, data) {
|
|
63
|
+
if (!TEXT_EXTENSIONS.includes(extensionOf(path))) return data;
|
|
64
|
+
let text;
|
|
65
|
+
try {
|
|
66
|
+
text = strictUtf8.decode(data);
|
|
67
|
+
} catch {
|
|
68
|
+
return data;
|
|
69
|
+
}
|
|
70
|
+
return text.includes("\r") ? Buffer.from(text.replace(/\r\n?/g, "\n"), "utf8") : data;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const byPath = (left, right) => Buffer.compare(Buffer.from(left.path, "utf8"), Buffer.from(right.path, "utf8"));
|
|
74
|
+
|
|
75
|
+
function checkEntries(entries, settings) {
|
|
76
|
+
const seen = new Set();
|
|
77
|
+
let total = 0;
|
|
78
|
+
for (const { path, data } of entries) {
|
|
79
|
+
const problem = checkPackagePath(path);
|
|
80
|
+
if (problem) throw new PackageError(problem.code, problem.message, String(path));
|
|
81
|
+
const folded = path.normalize("NFC").toLowerCase();
|
|
82
|
+
if (seen.has(folded)) throw new PackageError("duplicate", "the path appears more than once (paths are compared without case)", path);
|
|
83
|
+
seen.add(folded);
|
|
84
|
+
const kind = executableKind(data);
|
|
85
|
+
if (kind) throw new PackageError("executable", `${kind} executables are not allowed`, path);
|
|
86
|
+
total += data.length;
|
|
87
|
+
}
|
|
88
|
+
if (entries.length > settings.maxFiles) throw new PackageError("too-many-files", `more than ${settings.maxFiles} files`);
|
|
89
|
+
if (total > settings.maxUnpackedBytes) throw new PackageError("too-large", `unpacks to more than ${settings.maxUnpackedBytes} bytes`);
|
|
90
|
+
if (!entries.some((entry) => entry.path === MANIFEST_FILE)) throw new PackageError("manifest", `${MANIFEST_FILE} is missing at the top of the package`);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function parseManifest(entries) {
|
|
94
|
+
const file = entries.find((entry) => entry.path === MANIFEST_FILE);
|
|
95
|
+
try {
|
|
96
|
+
return JSON.parse(file.data.toString("utf8").replace(/^/, ""));
|
|
97
|
+
} catch {
|
|
98
|
+
throw new PackageError("manifest", "is not valid JSON", MANIFEST_FILE);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export const sha256Hex = (data) => createHash("sha256").update(data).digest("hex");
|
|
103
|
+
|
|
104
|
+
export function packageDigest(entries, options = {}) {
|
|
105
|
+
const settings = resolvePackageOptions(options);
|
|
106
|
+
const lines = entries
|
|
107
|
+
.filter((entry) => entry.path !== settings.signatureFile)
|
|
108
|
+
.map((entry) => ({ path: entry.path, hash: sha256Hex(entry.data) }))
|
|
109
|
+
.sort(byPath)
|
|
110
|
+
.map((entry) => `${entry.hash} ${entry.path}\n`);
|
|
111
|
+
return sha256Hex(`${settings.namespace}-package-digest/1\n${lines.join("")}`);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function packFiles(files, options = {}) {
|
|
115
|
+
const settings = resolvePackageOptions(options);
|
|
116
|
+
const normalize = options.normalizeText === false ? (path, data) => data : normalizeText;
|
|
117
|
+
const entries = files.map(({ path, data }) => ({ path, data: normalize(path, Buffer.isBuffer(data) ? data : Buffer.from(data)) })).sort(byPath);
|
|
118
|
+
checkEntries(entries, settings);
|
|
119
|
+
const zip = createZip(entries);
|
|
120
|
+
if (zip.length > settings.maxPackageBytes) throw new PackageError("too-large", `the package is ${zip.length} bytes, over ${settings.maxPackageBytes}`);
|
|
121
|
+
return { zip, digest: packageDigest(entries, settings), manifest: parseManifest(entries), files: entries };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export function collectFiles(dir) {
|
|
125
|
+
const walk = (folder, prefix) =>
|
|
126
|
+
readdirSync(folder).flatMap((name) => {
|
|
127
|
+
const full = join(folder, name);
|
|
128
|
+
const path = prefix + name;
|
|
129
|
+
const stat = lstatSync(full);
|
|
130
|
+
if (stat.isSymbolicLink()) throw new PackageError("symlink", "symbolic links are not allowed", path);
|
|
131
|
+
if (stat.isDirectory()) return walk(full, `${path}/`);
|
|
132
|
+
if (!stat.isFile()) throw new PackageError("special", "only regular files are allowed", path);
|
|
133
|
+
return [{ path, data: readFileSync(full) }];
|
|
134
|
+
});
|
|
135
|
+
return walk(dir, "");
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export const packDirectory = (dir, options = {}) => packFiles(collectFiles(dir), options);
|
|
139
|
+
|
|
140
|
+
export function readPackage(zip, options = {}) {
|
|
141
|
+
const settings = resolvePackageOptions(options);
|
|
142
|
+
if (!Buffer.isBuffer(zip)) throw new PackageError("zip", "expected the package bytes");
|
|
143
|
+
if (zip.length > settings.maxPackageBytes) throw new PackageError("too-large", `the package is ${zip.length} bytes, over ${settings.maxPackageBytes}`);
|
|
144
|
+
const entries = readZip(zip, settings);
|
|
145
|
+
checkEntries(entries, settings);
|
|
146
|
+
const signatureEntry = entries.find((entry) => entry.path === settings.signatureFile);
|
|
147
|
+
let signatures = null;
|
|
148
|
+
if (signatureEntry) {
|
|
149
|
+
try {
|
|
150
|
+
signatures = JSON.parse(signatureEntry.data.toString("utf8"));
|
|
151
|
+
} catch {
|
|
152
|
+
throw new PackageError("signature", "is not valid JSON", settings.signatureFile);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return {
|
|
156
|
+
files: entries.filter((entry) => entry !== signatureEntry),
|
|
157
|
+
manifest: parseManifest(entries),
|
|
158
|
+
digest: packageDigest(entries, settings),
|
|
159
|
+
signatures,
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function packageFileName(name, version, options = {}) {
|
|
164
|
+
const { extension } = resolvePackageOptions(options);
|
|
165
|
+
return `${String(name).replace(/^@/, "").replace(/\//g, "-")}-${version}${extension}`;
|
|
166
|
+
}
|
package/src/schema.d.mts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function manifestSchema(options?: { appKey?: string; categories?: readonly string[] }): Record<string, unknown>;
|
package/src/schema.mjs
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { DEFAULT_APP_KEY, DEFAULT_CATEGORIES, MANIFEST_VERSION, MAX_SCREENSHOTS, PLATFORMS, REQUIRED_LOCALES } from "./manifest.mjs";
|
|
2
|
+
|
|
3
|
+
const text = { type: "string", minLength: 1 };
|
|
4
|
+
const list = (items = text) => ({ type: "array", items, uniqueItems: true });
|
|
5
|
+
const path = { type: "string", minLength: 1, pattern: "^(?![A-Za-z]:)(?!/)(?!.*\\\\)(?!(?:.*/)?\\.\\.?(?:/|$)).+$" };
|
|
6
|
+
const localized = {
|
|
7
|
+
type: "object",
|
|
8
|
+
required: REQUIRED_LOCALES,
|
|
9
|
+
properties: Object.fromEntries(REQUIRED_LOCALES.map((locale) => [locale, text])),
|
|
10
|
+
additionalProperties: { type: "string" },
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export function manifestSchema({ appKey = DEFAULT_APP_KEY, categories = DEFAULT_CATEGORIES } = {}) {
|
|
14
|
+
const app = {
|
|
15
|
+
type: "object",
|
|
16
|
+
required: ["manifest", "displayName", "description", "icon", "categories"],
|
|
17
|
+
properties: {
|
|
18
|
+
manifest: { const: MANIFEST_VERSION },
|
|
19
|
+
displayName: localized,
|
|
20
|
+
description: localized,
|
|
21
|
+
icon: { ...path, pattern: `${path.pattern.slice(0, -1)}\\.(?:png|svg)$` },
|
|
22
|
+
categories: { ...list({ enum: categories }), minItems: 1 },
|
|
23
|
+
screenshots: {
|
|
24
|
+
type: "array",
|
|
25
|
+
maxItems: MAX_SCREENSHOTS,
|
|
26
|
+
items: { type: "object", required: ["path"], properties: { path, caption: localized } },
|
|
27
|
+
},
|
|
28
|
+
preview: { type: "boolean" },
|
|
29
|
+
platforms: list({ enum: PLATFORMS }),
|
|
30
|
+
host: path,
|
|
31
|
+
client: { type: "object", additionalProperties: path },
|
|
32
|
+
inject: { type: "object", properties: { required: list(), optional: list() } },
|
|
33
|
+
requires: { type: "object", propertyNames: { pattern: "^@[^/]+/[^/]+$" }, additionalProperties: text },
|
|
34
|
+
provides: list(),
|
|
35
|
+
replaces: list(),
|
|
36
|
+
slots: list(),
|
|
37
|
+
commands: {
|
|
38
|
+
type: "array",
|
|
39
|
+
items: {
|
|
40
|
+
type: "object",
|
|
41
|
+
required: ["id", "title"],
|
|
42
|
+
properties: { id: text, title: localized, keybinding: text },
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
network: list({ type: "string", pattern: "^(?:\\*\\.)?[a-z0-9.-]+$" }),
|
|
46
|
+
config: path,
|
|
47
|
+
experimental: list(),
|
|
48
|
+
nodeApis: { ...list(), description: "Written by the build: the Node modules the host part imports" },
|
|
49
|
+
builtWith: { type: "string", description: "Written by the build: the SDK version" },
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
return {
|
|
53
|
+
$schema: "https://json-schema.org/draft/2020-12/schema",
|
|
54
|
+
title: `${appKey} plugin package.json`,
|
|
55
|
+
type: "object",
|
|
56
|
+
required: ["name", "version", "type", "license", "repository", "engines", appKey],
|
|
57
|
+
properties: {
|
|
58
|
+
name: { type: "string", pattern: "^@[a-z0-9][a-z0-9._~-]*/[a-z0-9][a-z0-9._~-]*$", maxLength: 214 },
|
|
59
|
+
version: { type: "string", pattern: "^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-[0-9A-Za-z.-]+)?(?:\\+[0-9A-Za-z.-]+)?$" },
|
|
60
|
+
type: { const: "module" },
|
|
61
|
+
description: { type: "string" },
|
|
62
|
+
license: { ...text, not: { const: "UNLICENSED" } },
|
|
63
|
+
homepage: text,
|
|
64
|
+
repository: { anyOf: [text, { type: "object", required: ["url"], properties: { url: text } }] },
|
|
65
|
+
keywords: list(),
|
|
66
|
+
files: list(),
|
|
67
|
+
engines: { type: "object", required: [appKey], properties: { [appKey]: text } },
|
|
68
|
+
[appKey]: app,
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
}
|
package/src/semver.d.mts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export interface SemVer {
|
|
2
|
+
major: number;
|
|
3
|
+
minor: number;
|
|
4
|
+
patch: number;
|
|
5
|
+
pre: string[];
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export declare function parseVersion(text: unknown): SemVer | null;
|
|
9
|
+
export declare function isValidVersion(text: unknown): boolean;
|
|
10
|
+
export declare function compareVersions(left: string | SemVer, right: string | SemVer): number;
|
|
11
|
+
export declare function isValidRange(text: unknown): boolean;
|
|
12
|
+
export declare function satisfies(version: string, range: string): boolean;
|
package/src/semver.mjs
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
const VERSION = /^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
|
|
2
|
+
const PARTIAL = /^v?(\d+|[xX*])(?:\.(\d+|[xX*]))?(?:\.(\d+|[xX*]))?(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-.]+)?$/;
|
|
3
|
+
|
|
4
|
+
export function parseVersion(text) {
|
|
5
|
+
const match = typeof text === "string" ? VERSION.exec(text.trim()) : null;
|
|
6
|
+
if (!match) return null;
|
|
7
|
+
return { major: Number(match[1]), minor: Number(match[2]), patch: Number(match[3]), pre: match[4] ? match[4].split(".") : [] };
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export const isValidVersion = (text) => parseVersion(text) !== null;
|
|
11
|
+
|
|
12
|
+
function comparePre(left, right) {
|
|
13
|
+
if (!left.length || !right.length) return right.length - left.length;
|
|
14
|
+
for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
|
|
15
|
+
const a = left[index];
|
|
16
|
+
const b = right[index];
|
|
17
|
+
if (a === undefined) return -1;
|
|
18
|
+
if (b === undefined) return 1;
|
|
19
|
+
const numA = /^\d+$/.test(a);
|
|
20
|
+
const numB = /^\d+$/.test(b);
|
|
21
|
+
if (numA && numB && Number(a) !== Number(b)) return Number(a) < Number(b) ? -1 : 1;
|
|
22
|
+
if (numA !== numB) return numA ? -1 : 1;
|
|
23
|
+
if (a !== b) return a < b ? -1 : 1;
|
|
24
|
+
}
|
|
25
|
+
return 0;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function compareVersions(left, right) {
|
|
29
|
+
const a = typeof left === "string" ? parseVersion(left) : left;
|
|
30
|
+
const b = typeof right === "string" ? parseVersion(right) : right;
|
|
31
|
+
for (const key of ["major", "minor", "patch"]) if (a[key] !== b[key]) return a[key] < b[key] ? -1 : 1;
|
|
32
|
+
return comparePre(a.pre, b.pre);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const wild = (part) => part === undefined || /^[xX*]$/.test(part);
|
|
36
|
+
|
|
37
|
+
function partial(text) {
|
|
38
|
+
const match = PARTIAL.exec(text);
|
|
39
|
+
if (!match) return null;
|
|
40
|
+
const [, major, minor, patch, pre] = match;
|
|
41
|
+
if (wild(major)) return { any: true };
|
|
42
|
+
const parts = [major, minor, patch];
|
|
43
|
+
const known = parts.findIndex(wild);
|
|
44
|
+
const length = known < 0 ? 3 : known;
|
|
45
|
+
if (parts.slice(length).some((part) => !wild(part))) return null;
|
|
46
|
+
if (pre && length < 3) return null;
|
|
47
|
+
return { length, major: Number(major), minor: Number(minor) || 0, patch: Number(patch) || 0, pre: pre ? pre.split(".") : [] };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const at = (major, minor, patch, pre = []) => ({ major, minor, patch, pre });
|
|
51
|
+
const bound = (major, minor, patch) => ({ major, minor, patch, pre: ["0"], synthetic: true });
|
|
52
|
+
const next = (p) => (p.length === 1 ? bound(p.major + 1, 0, 0) : bound(p.major, p.minor + 1, 0));
|
|
53
|
+
const floor = (p) => at(p.major, p.minor, p.patch, p.pre);
|
|
54
|
+
|
|
55
|
+
function comparators(operator, text) {
|
|
56
|
+
const p = partial(text);
|
|
57
|
+
if (!p) return null;
|
|
58
|
+
if (p.any) return operator === "<" || operator === ">" ? [{ op: "<", version: bound(0, 0, 0) }] : [];
|
|
59
|
+
if (operator === "^") {
|
|
60
|
+
const upper = p.major > 0 || p.length === 1 ? bound(p.major + 1, 0, 0) : p.minor > 0 || p.length === 2 ? bound(0, p.minor + 1, 0) : bound(0, 0, p.patch + 1);
|
|
61
|
+
return [{ op: ">=", version: floor(p) }, { op: "<", version: upper }];
|
|
62
|
+
}
|
|
63
|
+
if (operator === "~") return [{ op: ">=", version: floor(p) }, { op: "<", version: p.length === 1 ? next(p) : bound(p.major, p.minor + 1, 0) }];
|
|
64
|
+
if (p.length < 3) {
|
|
65
|
+
if (operator === "" || operator === "=") return [{ op: ">=", version: floor(p) }, { op: "<", version: next(p) }];
|
|
66
|
+
if (operator === ">") return [{ op: ">=", version: next(p) }];
|
|
67
|
+
if (operator === "<=") return [{ op: "<", version: next(p) }];
|
|
68
|
+
}
|
|
69
|
+
return [{ op: operator || "=", version: floor(p) }];
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function parseSet(text) {
|
|
73
|
+
const hyphen = /^\s*(\S+)\s+-\s+(\S+)\s*$/.exec(text);
|
|
74
|
+
if (hyphen) {
|
|
75
|
+
const low = comparators(">=", hyphen[1]);
|
|
76
|
+
const high = partial(hyphen[2]);
|
|
77
|
+
if (!low || !high) return null;
|
|
78
|
+
if (high.any) return low;
|
|
79
|
+
return [...low, ...(high.length < 3 ? [{ op: "<", version: next(high) }] : [{ op: "<=", version: floor(high) }])];
|
|
80
|
+
}
|
|
81
|
+
const tokens = text.trim().replace(/(>=|<=|[<>=^~])\s+/g, "$1").split(/\s+/).filter(Boolean);
|
|
82
|
+
const set = [];
|
|
83
|
+
for (const token of tokens) {
|
|
84
|
+
const match = /^(>=|<=|[<>=^~]|)(.*)$/.exec(token);
|
|
85
|
+
const parsed = match && comparators(match[1], match[2]);
|
|
86
|
+
if (!parsed) return null;
|
|
87
|
+
set.push(...parsed);
|
|
88
|
+
}
|
|
89
|
+
return set;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function parseRange(text) {
|
|
93
|
+
if (typeof text !== "string" || text.trim() === "") return null;
|
|
94
|
+
const sets = text.split("||").map(parseSet);
|
|
95
|
+
return sets.some((set) => set === null) ? null : sets;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export const isValidRange = (text) => parseRange(text) !== null;
|
|
99
|
+
|
|
100
|
+
function test(comparator, version) {
|
|
101
|
+
const order = compareVersions(version, comparator.version);
|
|
102
|
+
return { "=": order === 0, ">": order > 0, ">=": order >= 0, "<": order < 0, "<=": order <= 0 }[comparator.op];
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const sameTuple = (a, b) => a.major === b.major && a.minor === b.minor && a.patch === b.patch;
|
|
106
|
+
|
|
107
|
+
export function satisfies(versionText, rangeText) {
|
|
108
|
+
const version = parseVersion(versionText);
|
|
109
|
+
const range = parseRange(rangeText);
|
|
110
|
+
if (!version || !range) return false;
|
|
111
|
+
return range.some((set) => {
|
|
112
|
+
if (!set.every((comparator) => test(comparator, version))) return false;
|
|
113
|
+
if (!version.pre.length) return true;
|
|
114
|
+
return set.some((comparator) => !comparator.version.synthetic && comparator.version.pre.length > 0 && sameTuple(comparator.version, version));
|
|
115
|
+
});
|
|
116
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import type { PluginManifest } from "./manifest.mjs";
|
|
2
|
+
import type { PackageEntry, PackageOptions } from "./package.mjs";
|
|
3
|
+
|
|
4
|
+
export type SignatureRole = "author" | "market";
|
|
5
|
+
|
|
6
|
+
export interface TrustedKey {
|
|
7
|
+
keyId: string;
|
|
8
|
+
publicKey: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface SignatureEntry {
|
|
12
|
+
role: SignatureRole;
|
|
13
|
+
keyId: string;
|
|
14
|
+
signature: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface SignatureSubject {
|
|
18
|
+
role: SignatureRole;
|
|
19
|
+
name: string;
|
|
20
|
+
version: string;
|
|
21
|
+
digest: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface SignatureFile {
|
|
25
|
+
format: 1;
|
|
26
|
+
name: string;
|
|
27
|
+
version: string;
|
|
28
|
+
digest: string;
|
|
29
|
+
signatures: SignatureEntry[];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface VerifyPackageResult {
|
|
33
|
+
manifest: PluginManifest;
|
|
34
|
+
digest: string;
|
|
35
|
+
files: PackageEntry[];
|
|
36
|
+
author: string | null;
|
|
37
|
+
market: string | null;
|
|
38
|
+
signed: boolean;
|
|
39
|
+
problems: string[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface SigningKeyObject {
|
|
43
|
+
readonly asymmetricKeyType?: string;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export type PrivateKeyInput = SigningKeyObject | string | Uint8Array;
|
|
47
|
+
|
|
48
|
+
export declare const SIGNATURE_FORMAT: 1;
|
|
49
|
+
export declare const SIGNATURE_ROLES: readonly SignatureRole[];
|
|
50
|
+
|
|
51
|
+
export declare function keyIdOf(raw: Uint8Array): string;
|
|
52
|
+
export declare function publicKeyOf(privateKey: PrivateKeyInput): TrustedKey;
|
|
53
|
+
export declare function generateSigningKey(): TrustedKey & { privateKey: SigningKeyObject };
|
|
54
|
+
export declare function signatureText(subject: SignatureSubject, options?: PackageOptions): string;
|
|
55
|
+
export declare function signDigest(subject: SignatureSubject, privateKey: PrivateKeyInput, options?: PackageOptions): SignatureEntry;
|
|
56
|
+
export declare function verifyDigestSignature(
|
|
57
|
+
entry: unknown,
|
|
58
|
+
subject: SignatureSubject,
|
|
59
|
+
keys: readonly TrustedKey[] | undefined,
|
|
60
|
+
options?: PackageOptions,
|
|
61
|
+
): string | null;
|
|
62
|
+
export declare function signatureFileFor(manifest: { name: string; version: string }, digest: string, signatures?: SignatureEntry[]): SignatureFile;
|
|
63
|
+
export declare function signPackage(zip: Uint8Array, role: SignatureRole, privateKey: PrivateKeyInput, options?: PackageOptions): Uint8Array;
|
|
64
|
+
export declare function verifyPackage(
|
|
65
|
+
zip: Uint8Array,
|
|
66
|
+
keys?: { author?: readonly TrustedKey[]; market?: readonly TrustedKey[] },
|
|
67
|
+
options?: PackageOptions,
|
|
68
|
+
): VerifyPackageResult;
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, sign, verify } from "node:crypto";
|
|
2
|
+
import { PackageError, packFiles, readPackage, resolvePackageOptions } from "./package.mjs";
|
|
3
|
+
|
|
4
|
+
export const SIGNATURE_FORMAT = 1;
|
|
5
|
+
export const SIGNATURE_ROLES = ["author", "market"];
|
|
6
|
+
const SPKI_HEX = "302a300506032b6570032100";
|
|
7
|
+
const SPKI_PREFIX = Buffer.from(SPKI_HEX, "hex");
|
|
8
|
+
const HEX64 = /^[0-9a-f]{64}$/;
|
|
9
|
+
|
|
10
|
+
export const keyIdOf = (raw) => createHash("sha256").update(raw).digest("hex").slice(0, 16);
|
|
11
|
+
|
|
12
|
+
function toPrivateKey(key) {
|
|
13
|
+
const object = typeof key === "string" || Buffer.isBuffer(key) ? createPrivateKey(key) : key;
|
|
14
|
+
if (object?.asymmetricKeyType !== "ed25519") throw new TypeError("signing keys must be Ed25519 private keys");
|
|
15
|
+
return object;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function publicKeyOf(privateKey) {
|
|
19
|
+
const raw = createPublicKey(toPrivateKey(privateKey)).export({ format: "der", type: "spki" }).subarray(SPKI_PREFIX.length);
|
|
20
|
+
return { keyId: keyIdOf(raw), publicKey: raw.toString("base64") };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function generateSigningKey() {
|
|
24
|
+
const { privateKey } = generateKeyPairSync("ed25519");
|
|
25
|
+
return { privateKey, ...publicKeyOf(privateKey) };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function checkSubject({ role, name, version, digest }) {
|
|
29
|
+
if (!SIGNATURE_ROLES.includes(role)) throw new TypeError(`role must be one of ${SIGNATURE_ROLES.join(", ")}`);
|
|
30
|
+
for (const [key, value] of Object.entries({ name, version })) {
|
|
31
|
+
if (typeof value !== "string" || value === "" || /[\n\r]/.test(value)) throw new TypeError(`${key} must be one line of text`);
|
|
32
|
+
}
|
|
33
|
+
if (typeof digest !== "string" || !HEX64.test(digest)) throw new TypeError("digest must be a lowercase SHA-256 hex string");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function signatureText(subject, options = {}) {
|
|
37
|
+
checkSubject(subject);
|
|
38
|
+
const { namespace } = resolvePackageOptions(options);
|
|
39
|
+
return `${namespace}-package-signature/1\n${subject.role}\n${subject.name}\n${subject.version}\n${subject.digest}`;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function signDigest(subject, privateKey, options = {}) {
|
|
43
|
+
const key = toPrivateKey(privateKey);
|
|
44
|
+
const { keyId } = publicKeyOf(key);
|
|
45
|
+
return { role: subject.role, keyId, signature: sign(null, Buffer.from(signatureText(subject, options)), key).toString("base64") };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function verifyDigestSignature(entry, subject, keys, options = {}) {
|
|
49
|
+
if (!entry || typeof entry.signature !== "string" || entry.role !== subject.role) return null;
|
|
50
|
+
const key = (keys ?? []).find((item) => item.keyId === entry.keyId);
|
|
51
|
+
if (!key || typeof key.publicKey !== "string") return null;
|
|
52
|
+
const raw = Buffer.from(key.publicKey, "base64");
|
|
53
|
+
if (raw.length !== 32 || keyIdOf(raw) !== key.keyId) return null;
|
|
54
|
+
try {
|
|
55
|
+
const publicKey = createPublicKey({ key: Buffer.concat([SPKI_PREFIX, raw]), format: "der", type: "spki" });
|
|
56
|
+
return verify(null, Buffer.from(signatureText(subject, options)), publicKey, Buffer.from(entry.signature, "base64")) ? key.keyId : null;
|
|
57
|
+
} catch {
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function signatureFileFor(manifest, digest, signatures = []) {
|
|
63
|
+
return { format: SIGNATURE_FORMAT, name: manifest.name, version: manifest.version, digest, signatures };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function sameSubject(file, manifest, digest) {
|
|
67
|
+
return file && file.format === SIGNATURE_FORMAT && file.name === manifest.name && file.version === manifest.version && file.digest === digest && Array.isArray(file.signatures);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function signPackage(zip, role, privateKey, options = {}) {
|
|
71
|
+
const settings = resolvePackageOptions(options);
|
|
72
|
+
const { files, manifest, digest, signatures } = readPackage(zip, settings);
|
|
73
|
+
const entry = signDigest({ role, name: manifest.name, version: manifest.version, digest }, privateKey, settings);
|
|
74
|
+
const kept = sameSubject(signatures, manifest, digest) ? signatures.signatures.filter((item) => !(item.role === role && item.keyId === entry.keyId)) : [];
|
|
75
|
+
const file = signatureFileFor(manifest, digest, [...kept, entry].sort((a, b) => SIGNATURE_ROLES.indexOf(a.role) - SIGNATURE_ROLES.indexOf(b.role) || (a.keyId < b.keyId ? -1 : 1)));
|
|
76
|
+
const data = Buffer.from(`${JSON.stringify(file, null, 2)}\n`, "utf8");
|
|
77
|
+
const packed = packFiles([...files, { path: settings.signatureFile, data }], { ...settings, normalizeText: false });
|
|
78
|
+
if (packed.digest !== digest) throw new PackageError("signature", "signing changed the package digest");
|
|
79
|
+
return packed.zip;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function verifyPackage(zip, keys = {}, options = {}) {
|
|
83
|
+
const settings = resolvePackageOptions(options);
|
|
84
|
+
const { files, manifest, digest, signatures } = readPackage(zip, settings);
|
|
85
|
+
const result = { manifest, digest, files, author: null, market: null, signed: signatures !== null, problems: [] };
|
|
86
|
+
if (signatures === null) return result;
|
|
87
|
+
if (!sameSubject(signatures, manifest, digest)) {
|
|
88
|
+
result.problems.push("the signature file does not match this package's name, version or digest");
|
|
89
|
+
return result;
|
|
90
|
+
}
|
|
91
|
+
const subject = { name: manifest.name, version: manifest.version, digest };
|
|
92
|
+
for (const entry of signatures.signatures) {
|
|
93
|
+
if (!SIGNATURE_ROLES.includes(entry?.role)) {
|
|
94
|
+
result.problems.push(`unknown signature role ${JSON.stringify(entry?.role)}`);
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
const keyId = verifyDigestSignature(entry, { ...subject, role: entry.role }, keys[entry.role], settings);
|
|
98
|
+
if (keyId && !result[entry.role]) result[entry.role] = keyId;
|
|
99
|
+
if (!keyId) result.problems.push(`${entry.role} signature ${entry.keyId ?? "?"} does not verify with the trusted keys`);
|
|
100
|
+
}
|
|
101
|
+
return result;
|
|
102
|
+
}
|
package/src/zip.d.mts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export interface PackageEntry {
|
|
2
|
+
path: string;
|
|
3
|
+
data: Uint8Array;
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export declare class PackageError extends Error {
|
|
7
|
+
constructor(code: string, message: string, path?: string);
|
|
8
|
+
code: string;
|
|
9
|
+
path?: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export declare function createZip(entries: readonly PackageEntry[]): Uint8Array;
|
|
13
|
+
export declare function readZip(zip: Uint8Array, limits: { maxFiles: number; maxUnpackedBytes: number }): PackageEntry[];
|
|
14
|
+
export declare function zipEntryNames(data: Uint8Array): string[];
|
package/src/zip.mjs
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { crc32, deflateRawSync, inflateRawSync } from "node:zlib";
|
|
2
|
+
|
|
3
|
+
const LOCAL = 0x04034b50;
|
|
4
|
+
const CENTRAL = 0x02014b50;
|
|
5
|
+
const END = 0x06054b50;
|
|
6
|
+
const DOS_DATE = (0 << 9) | (1 << 5) | 1;
|
|
7
|
+
const UTF8 = 0x0800;
|
|
8
|
+
const UNIX = 3;
|
|
9
|
+
const FILE_MODE = 0o100644;
|
|
10
|
+
|
|
11
|
+
export class PackageError extends Error {
|
|
12
|
+
constructor(code, message, path) {
|
|
13
|
+
super(path ? `${path}: ${message}` : message);
|
|
14
|
+
this.name = "PackageError";
|
|
15
|
+
this.code = code;
|
|
16
|
+
if (path) this.path = path;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function createZip(entries) {
|
|
21
|
+
const locals = [];
|
|
22
|
+
const centrals = [];
|
|
23
|
+
let offset = 0;
|
|
24
|
+
for (const { path, data } of entries) {
|
|
25
|
+
const name = Buffer.from(path, "utf8");
|
|
26
|
+
const compressed = deflateRawSync(data, { level: 9 });
|
|
27
|
+
const crc = crc32(data);
|
|
28
|
+
const local = Buffer.alloc(30);
|
|
29
|
+
local.writeUInt32LE(LOCAL, 0);
|
|
30
|
+
local.writeUInt16LE(20, 4);
|
|
31
|
+
local.writeUInt16LE(UTF8, 6);
|
|
32
|
+
local.writeUInt16LE(8, 8);
|
|
33
|
+
local.writeUInt16LE(0, 10);
|
|
34
|
+
local.writeUInt16LE(DOS_DATE, 12);
|
|
35
|
+
local.writeUInt32LE(crc, 14);
|
|
36
|
+
local.writeUInt32LE(compressed.length, 18);
|
|
37
|
+
local.writeUInt32LE(data.length, 22);
|
|
38
|
+
local.writeUInt16LE(name.length, 26);
|
|
39
|
+
locals.push(local, name, compressed);
|
|
40
|
+
const central = Buffer.alloc(46);
|
|
41
|
+
central.writeUInt32LE(CENTRAL, 0);
|
|
42
|
+
central.writeUInt16LE((UNIX << 8) | 20, 4);
|
|
43
|
+
central.writeUInt16LE(20, 6);
|
|
44
|
+
central.writeUInt16LE(UTF8, 8);
|
|
45
|
+
central.writeUInt16LE(8, 10);
|
|
46
|
+
central.writeUInt16LE(0, 12);
|
|
47
|
+
central.writeUInt16LE(DOS_DATE, 14);
|
|
48
|
+
central.writeUInt32LE(crc, 16);
|
|
49
|
+
central.writeUInt32LE(compressed.length, 20);
|
|
50
|
+
central.writeUInt32LE(data.length, 24);
|
|
51
|
+
central.writeUInt16LE(name.length, 28);
|
|
52
|
+
central.writeUInt32LE((FILE_MODE << 16) >>> 0, 38);
|
|
53
|
+
central.writeUInt32LE(offset, 42);
|
|
54
|
+
centrals.push(central, name);
|
|
55
|
+
offset += local.length + name.length + compressed.length;
|
|
56
|
+
}
|
|
57
|
+
const directory = Buffer.concat(centrals);
|
|
58
|
+
const end = Buffer.alloc(22);
|
|
59
|
+
end.writeUInt32LE(END, 0);
|
|
60
|
+
end.writeUInt16LE(entries.length, 8);
|
|
61
|
+
end.writeUInt16LE(entries.length, 10);
|
|
62
|
+
end.writeUInt32LE(directory.length, 12);
|
|
63
|
+
end.writeUInt32LE(offset, 16);
|
|
64
|
+
return Buffer.concat([...locals, directory, end]);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function zipEntryNames(data) {
|
|
68
|
+
const names = new Set();
|
|
69
|
+
for (const [signature, nameAt, lengthAt] of [[Buffer.from([0x50, 0x4b, 0x03, 0x04]), 30, 26], [Buffer.from([0x50, 0x4b, 0x01, 0x02]), 46, 28]]) {
|
|
70
|
+
for (let at = data.indexOf(signature); at >= 0 && at + nameAt <= data.length; at = data.indexOf(signature, at + 4)) {
|
|
71
|
+
const length = data.readUInt16LE(at + lengthAt);
|
|
72
|
+
if (at + nameAt + length <= data.length) names.add(data.toString("utf8", at + nameAt, at + nameAt + length));
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return [...names];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function findEnd(zip) {
|
|
79
|
+
const earliest = Math.max(0, zip.length - 22 - 0xffff);
|
|
80
|
+
for (let at = zip.length - 22; at >= earliest; at -= 1) {
|
|
81
|
+
if (zip.readUInt32LE(at) === END && at + 22 + zip.readUInt16LE(at + 20) === zip.length) return at;
|
|
82
|
+
}
|
|
83
|
+
throw new PackageError("zip", "not a zip file");
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function entryKind(madeBy, external, name) {
|
|
87
|
+
const mode = madeBy >> 8 === UNIX ? external >>> 16 : 0;
|
|
88
|
+
const type = mode & 0o170000;
|
|
89
|
+
if (type === 0o120000) return "symlink";
|
|
90
|
+
if (type === 0o040000 || (external & 0x10) !== 0 || name.endsWith("/")) return "directory";
|
|
91
|
+
if (type !== 0 && type !== 0o100000) return "special";
|
|
92
|
+
return "file";
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
96
|
+
|
|
97
|
+
export function readZip(zip, { maxFiles, maxUnpackedBytes }) {
|
|
98
|
+
if (!Buffer.isBuffer(zip) || zip.length < 22) throw new PackageError("zip", "not a zip file");
|
|
99
|
+
const end = findEnd(zip);
|
|
100
|
+
if (zip.readUInt16LE(end + 4) !== 0 || zip.readUInt16LE(end + 6) !== 0) throw new PackageError("zip", "multi-disk zips are not supported");
|
|
101
|
+
const count = zip.readUInt16LE(end + 10);
|
|
102
|
+
const size = zip.readUInt32LE(end + 12);
|
|
103
|
+
let at = zip.readUInt32LE(end + 16);
|
|
104
|
+
if (count === 0xffff || at === 0xffffffff) throw new PackageError("zip", "zip64 is not supported");
|
|
105
|
+
if (count > maxFiles) throw new PackageError("too-many-files", `more than ${maxFiles} files`);
|
|
106
|
+
if (at + size > end) throw new PackageError("zip", "broken zip directory");
|
|
107
|
+
const entries = [];
|
|
108
|
+
let total = 0;
|
|
109
|
+
for (let index = 0; index < count; index += 1) {
|
|
110
|
+
if (at + 46 > end || zip.readUInt32LE(at) !== CENTRAL) throw new PackageError("zip", "broken zip directory");
|
|
111
|
+
const madeBy = zip.readUInt16LE(at + 4);
|
|
112
|
+
const flags = zip.readUInt16LE(at + 8);
|
|
113
|
+
const method = zip.readUInt16LE(at + 10);
|
|
114
|
+
const crc = zip.readUInt32LE(at + 16);
|
|
115
|
+
const compressedSize = zip.readUInt32LE(at + 20);
|
|
116
|
+
const declared = zip.readUInt32LE(at + 24);
|
|
117
|
+
const nameLength = zip.readUInt16LE(at + 28);
|
|
118
|
+
const extraLength = zip.readUInt16LE(at + 30);
|
|
119
|
+
const commentLength = zip.readUInt16LE(at + 32);
|
|
120
|
+
const external = zip.readUInt32LE(at + 38);
|
|
121
|
+
const local = zip.readUInt32LE(at + 42);
|
|
122
|
+
const nameBytes = zip.subarray(at + 46, at + 46 + nameLength);
|
|
123
|
+
let path;
|
|
124
|
+
try {
|
|
125
|
+
path = decoder.decode(nameBytes);
|
|
126
|
+
} catch {
|
|
127
|
+
throw new PackageError("path", "a file name is not UTF-8");
|
|
128
|
+
}
|
|
129
|
+
at += 46 + nameLength + extraLength + commentLength;
|
|
130
|
+
if (flags & 0x1) throw new PackageError("zip", "encrypted entries are not allowed", path);
|
|
131
|
+
const kind = entryKind(madeBy, external, path);
|
|
132
|
+
if (kind === "symlink") throw new PackageError("symlink", "symbolic links are not allowed", path);
|
|
133
|
+
if (kind === "special") throw new PackageError("special", "only regular files are allowed", path);
|
|
134
|
+
if (kind === "directory") continue;
|
|
135
|
+
if (method !== 0 && method !== 8) throw new PackageError("zip", `compression method ${method} is not supported`, path);
|
|
136
|
+
total += declared;
|
|
137
|
+
if (total > maxUnpackedBytes) throw new PackageError("too-large", `unpacks to more than ${maxUnpackedBytes} bytes`);
|
|
138
|
+
if (local + 30 > zip.length || zip.readUInt32LE(local) !== LOCAL) throw new PackageError("zip", "broken local header", path);
|
|
139
|
+
const start = local + 30 + zip.readUInt16LE(local + 26) + zip.readUInt16LE(local + 28);
|
|
140
|
+
if (start + compressedSize > zip.length) throw new PackageError("zip", "entry runs past the end of the file", path);
|
|
141
|
+
const stored = zip.subarray(start, start + compressedSize);
|
|
142
|
+
let data;
|
|
143
|
+
try {
|
|
144
|
+
data = method === 8 ? inflateRawSync(stored, { maxOutputLength: Math.max(declared, 1) }) : Buffer.from(stored);
|
|
145
|
+
} catch {
|
|
146
|
+
throw new PackageError("too-large", "entry is larger than it says or is corrupt", path);
|
|
147
|
+
}
|
|
148
|
+
if (data.length !== declared || crc32(data) !== crc) throw new PackageError("zip", "entry size or checksum does not match", path);
|
|
149
|
+
entries.push({ path, data });
|
|
150
|
+
}
|
|
151
|
+
return entries;
|
|
152
|
+
}
|