@nesso-how/plugin 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,224 @@
1
+ import { z } from 'zod';
2
+ import parseVersion from 'semver/functions/parse.js';
3
+ import validateName from 'validate-npm-package-name';
4
+ import { checkMessageSize, parseDefinition, parsePluginI18n, parsePluginManifest, parseOrThrow, PluginError, sha256Hex, } from './runtime.js';
5
+ export const packageLimits = {
6
+ entry: 16 * 1024 * 1024,
7
+ font: 4 * 1024 * 1024,
8
+ fonts: 32,
9
+ record: 32 * 1024 * 1024,
10
+ installed: 32,
11
+ total: 128 * 1024 * 1024,
12
+ };
13
+ const author = z
14
+ .union([z.string().max(512), z.object({ name: z.string().max(128) })])
15
+ .transform((value) => (typeof value === 'string' ? value : value.name).split(/[<(]/)[0].trim())
16
+ .pipe(z
17
+ .string()
18
+ .min(1)
19
+ .max(128)
20
+ .regex(/^\P{Cc}+$/u))
21
+ .optional()
22
+ .catch(undefined);
23
+ const repository = z
24
+ .union([z.string().max(2048), z.object({ url: z.string().max(2048) })])
25
+ .transform((value) => {
26
+ const source = typeof value === 'string' ? value : value.url;
27
+ if (/[\p{Cc}\s\\]/u.test(source))
28
+ return undefined;
29
+ try {
30
+ const url = new URL(source.replace(/^git\+/, '').replace(/^github:/, 'https://github.com/'));
31
+ const pathname = url.pathname.replace(/\/$/, '').replace(/\.git$/, '');
32
+ if (url.origin !== 'https://github.com' ||
33
+ url.username ||
34
+ url.password ||
35
+ url.search ||
36
+ url.hash ||
37
+ !/^\/[a-zA-Z0-9][a-zA-Z0-9-]*\/[a-zA-Z0-9._-]+$/.test(pathname))
38
+ return undefined;
39
+ return `${url.origin}${pathname}`;
40
+ }
41
+ catch {
42
+ return undefined;
43
+ }
44
+ })
45
+ .optional()
46
+ .catch(undefined);
47
+ const identity = z.object({
48
+ name: z
49
+ .string()
50
+ .max(214)
51
+ .refine((value) => validateName(value).validForNewPackages, 'Expected a valid npm package name'),
52
+ version: z
53
+ .string()
54
+ .max(128)
55
+ .refine((value) => {
56
+ const parsed = parseVersion(value);
57
+ return (parsed !== null &&
58
+ `${parsed.version}${parsed.build.length ? `+${parsed.build.join('.')}` : ''}` === value);
59
+ }, 'Expected an exact semantic version'),
60
+ author,
61
+ repository,
62
+ nesso: z.unknown().optional(),
63
+ i18n: z.unknown().optional(),
64
+ });
65
+ const canonical = (value) => {
66
+ if (Array.isArray(value))
67
+ return `[${value.map(canonical).join(',')}]`;
68
+ if (value !== null && typeof value === 'object')
69
+ return `{${Object.entries(value)
70
+ .filter(([, item]) => item !== undefined)
71
+ .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
72
+ .map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`)
73
+ .join(',')}}`;
74
+ return JSON.stringify(value);
75
+ };
76
+ export function parsePackageIdentity(value) {
77
+ return parseOrThrow(identity, value);
78
+ }
79
+ export async function preparePluginPackage(input) {
80
+ checkMessageSize(input.manifest, 64 * 1024);
81
+ const { name, version, author, repository, nesso: declaration, i18n: translations, } = parsePackageIdentity(input.manifest);
82
+ const nesso = parsePluginManifest(declaration);
83
+ const i18n = parsePluginI18n(translations);
84
+ if (!Array.isArray(input.files) ||
85
+ !input.files.length ||
86
+ input.files.length > (nesso.kind === 'theme' ? packageLimits.fonts + 1 : 1))
87
+ throw new PluginError('invalid-input', [
88
+ { path: 'files', message: 'Expected one entry and supported local theme fonts only' },
89
+ ]);
90
+ const paths = new Set();
91
+ const fonts = [];
92
+ const files = [];
93
+ let bytes;
94
+ let admitted = 0;
95
+ for (const file of input.files) {
96
+ if (!file ||
97
+ typeof file.path !== 'string' ||
98
+ file.path.length > 240 ||
99
+ paths.has(file.path) ||
100
+ !(file.bytes instanceof Uint8Array) ||
101
+ !file.bytes.byteLength ||
102
+ file.bytes.byteLength > (file.path === nesso.entry ? packageLimits.entry : packageLimits.font))
103
+ throw new PluginError('invalid-input', [
104
+ { path: 'files', message: 'Invalid, duplicate, or oversized package file' },
105
+ ]);
106
+ paths.add(file.path);
107
+ admitted +=
108
+ file.path === nesso.entry ? file.bytes.byteLength : Math.ceil(file.bytes.byteLength / 3) * 4;
109
+ if (admitted > packageLimits.record)
110
+ throw new PluginError('invalid-input', [
111
+ { path: 'files', message: 'Package record budget exceeded' },
112
+ ]);
113
+ const content = new Uint8Array(file.bytes);
114
+ if (file.path === nesso.entry)
115
+ bytes = content;
116
+ else {
117
+ if (nesso.kind !== 'theme' ||
118
+ !/^(?:[\w-]+\/)*[\w-]+\.woff2$/.test(file.path) ||
119
+ new TextDecoder().decode(content.subarray(0, 4)) !== 'wOF2')
120
+ throw new PluginError('invalid-input', [
121
+ { path: file.path, message: 'Expected a package-local WOFF2 font' },
122
+ ]);
123
+ let binary = '';
124
+ for (let offset = 0; offset < content.length; offset += 32_768)
125
+ binary += String.fromCharCode(...content.subarray(offset, offset + 32_768));
126
+ fonts.push({ path: file.path, data: btoa(binary) });
127
+ }
128
+ files.push({ path: file.path, size: content.byteLength, sha256: await sha256Hex(content) });
129
+ }
130
+ if (!bytes)
131
+ throw new PluginError('invalid-input', [
132
+ { path: 'nesso.entry', message: 'Missing plugin entry' },
133
+ ]);
134
+ let code;
135
+ try {
136
+ code = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
137
+ }
138
+ catch {
139
+ throw new PluginError('invalid-input', [
140
+ { path: 'files', message: 'Expected UTF-8 entry text' },
141
+ ]);
142
+ }
143
+ if (nesso.kind !== 'actions') {
144
+ let raw;
145
+ try {
146
+ raw = JSON.parse(code);
147
+ }
148
+ catch {
149
+ throw new PluginError('invalid-input', [
150
+ { path: nesso.entry, message: 'Expected a JSON definition' },
151
+ ]);
152
+ }
153
+ parseDefinition(nesso.kind, raw);
154
+ }
155
+ const order = (left, right) => left.path < right.path ? -1 : left.path > right.path ? 1 : 0;
156
+ const index = { name, version, author, repository, nesso, i18n, files: files.sort(order) };
157
+ const prepared = {
158
+ name,
159
+ version,
160
+ author,
161
+ repository,
162
+ nesso,
163
+ i18n,
164
+ code,
165
+ fonts: fonts.sort(order),
166
+ contentId: await sha256Hex(new TextEncoder().encode(canonical(index))),
167
+ };
168
+ if (new TextEncoder().encode(JSON.stringify(prepared)).byteLength > packageLimits.record)
169
+ throw new PluginError('invalid-input', [
170
+ { path: 'files', message: 'Package record budget exceeded' },
171
+ ]);
172
+ return prepared;
173
+ }
174
+ export function packageFonts(value) {
175
+ if (!Array.isArray(value.fonts) || value.fonts.length > packageLimits.fonts)
176
+ throw new PluginError('invalid-input', [
177
+ { path: 'fonts', message: 'Invalid installed font assets' },
178
+ ]);
179
+ return new Map(value.fonts.map((font) => {
180
+ if (!font ||
181
+ typeof font.path !== 'string' ||
182
+ typeof font.data !== 'string' ||
183
+ font.data.length > Math.ceil(packageLimits.font / 3) * 4)
184
+ throw new PluginError('invalid-input', [
185
+ { path: 'fonts', message: 'Invalid font encoding or budget' },
186
+ ]);
187
+ try {
188
+ return [font.path, Uint8Array.from(atob(font.data), (character) => character.charCodeAt(0))];
189
+ }
190
+ catch {
191
+ throw new PluginError('invalid-input', [
192
+ { path: 'fonts', message: 'Invalid font encoding' },
193
+ ]);
194
+ }
195
+ }));
196
+ }
197
+ export async function verifyPluginPackage(value) {
198
+ if (!value || typeof value.code !== 'string' || value.code.length > packageLimits.entry)
199
+ throw new PluginError('invalid-input', [
200
+ { path: 'package', message: 'Invalid installed plugin package' },
201
+ ]);
202
+ const fonts = packageFonts(value);
203
+ if (fonts.size !== value.fonts.length)
204
+ throw new PluginError('invalid-input', [{ path: 'fonts', message: 'Duplicate font assets' }]);
205
+ const prepared = await preparePluginPackage({
206
+ manifest: {
207
+ name: value.name,
208
+ version: value.version,
209
+ author: value.author,
210
+ repository: value.repository,
211
+ nesso: value.nesso,
212
+ i18n: value.i18n,
213
+ },
214
+ files: [
215
+ { path: value.nesso?.entry, bytes: new TextEncoder().encode(value.code) },
216
+ ...[...fonts].map(([path, bytes]) => ({ path, bytes })),
217
+ ],
218
+ });
219
+ if (prepared.contentId !== value.contentId)
220
+ throw new PluginError('denied', [
221
+ { path: 'contentId', message: 'Package content does not match its approval' },
222
+ ]);
223
+ return prepared;
224
+ }