@shiqianjiang/ceru-plugin-core 0.2.0 → 0.2.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/LICENSE +21 -0
- package/NOTICE +1 -0
- package/README.md +5 -1
- package/assets/catalog.json +1 -0
- package/assets/node-globals.js +2033 -0
- package/assets/preload.cjs +12 -0
- package/assets/sandbox.js +67 -0
- package/dist/electron.d.ts +17 -0
- package/dist/electron.js +139 -0
- package/dist/index.d.ts +6 -1
- package/dist/index.js +69 -10
- package/dist/network.d.ts +2 -0
- package/dist/network.js +72 -0
- package/dist/node-worker.d.ts +1 -0
- package/dist/node-worker.js +90 -0
- package/dist/node.d.ts +14 -0
- package/dist/node.js +94 -0
- package/dist/socket-broker.d.ts +23 -0
- package/dist/socket-broker.js +229 -0
- package/package.json +61 -28
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Artifact } from '@shiqianjiang/ceru-plugin-issuer';
|
|
2
|
+
/** Chromium's OS sandbox executes plugin code; only JSON messages cross IPC. */
|
|
3
|
+
export declare class ElectronPluginSandbox {
|
|
4
|
+
private readonly rpc;
|
|
5
|
+
private readonly event;
|
|
6
|
+
static prewarm(): Promise<void>;
|
|
7
|
+
private window?;
|
|
8
|
+
private readonly generation;
|
|
9
|
+
private readonly pending;
|
|
10
|
+
private listener?;
|
|
11
|
+
constructor(rpc: (method: string, data: any) => Promise<any>, event: (type: string, data: any) => void);
|
|
12
|
+
start(artifact: Artifact, surfaceId?: string): Promise<void>;
|
|
13
|
+
send(type: string, data: any): Promise<any>;
|
|
14
|
+
show(): void;
|
|
15
|
+
invoke(kind: string, target: string, method: string, args: any[], signal?: AbortSignal): Promise<any>;
|
|
16
|
+
dispose(): void;
|
|
17
|
+
}
|
package/dist/electron.js
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { BrowserWindow, ipcMain, session } from 'electron';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { readFile } from 'node:fs/promises';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
let cachedAssets;
|
|
6
|
+
function assets() {
|
|
7
|
+
return cachedAssets ??= Promise.all([
|
|
8
|
+
readFile(new URL('../assets/sandbox.js', import.meta.url), 'utf8'),
|
|
9
|
+
readFile(new URL('../assets/catalog.json', import.meta.url), 'utf8')
|
|
10
|
+
]);
|
|
11
|
+
}
|
|
12
|
+
/** Chromium's OS sandbox executes plugin code; only JSON messages cross IPC. */
|
|
13
|
+
export class ElectronPluginSandbox {
|
|
14
|
+
rpc;
|
|
15
|
+
event;
|
|
16
|
+
static async prewarm() { await assets(); }
|
|
17
|
+
window;
|
|
18
|
+
generation = randomUUID();
|
|
19
|
+
pending = new Map();
|
|
20
|
+
listener;
|
|
21
|
+
constructor(rpc, event) {
|
|
22
|
+
this.rpc = rpc;
|
|
23
|
+
this.event = event;
|
|
24
|
+
}
|
|
25
|
+
async start(artifact, surfaceId) {
|
|
26
|
+
const surface = artifact.header.manifest.modules.surfaces?.find(item => item.id === surfaceId);
|
|
27
|
+
const moduleId = surfaceId ? surface?.entry : artifact.header.manifest.modules.logic?.entry;
|
|
28
|
+
if (!moduleId) {
|
|
29
|
+
if (surfaceId)
|
|
30
|
+
throw new Error('Unknown surface');
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
const code = artifact.modules[moduleId];
|
|
34
|
+
if (!code)
|
|
35
|
+
throw new Error('Missing plugin entry');
|
|
36
|
+
const [runtime, catalog] = await assets();
|
|
37
|
+
const isolatedSession = session.fromPartition('ceru-plugin-' + this.generation);
|
|
38
|
+
isolatedSession.setPermissionRequestHandler((_contents, _permission, callback) => callback(false));
|
|
39
|
+
isolatedSession.setPermissionCheckHandler(() => false);
|
|
40
|
+
isolatedSession.webRequest.onBeforeRequest((details, callback) => callback({ cancel: !/^(data:|about:)/.test(details.url) }));
|
|
41
|
+
const win = new BrowserWindow({
|
|
42
|
+
show: false, width: 1040, height: 760, title: artifact.header.manifest.name,
|
|
43
|
+
webPreferences: {
|
|
44
|
+
session: isolatedSession, sandbox: true, contextIsolation: true, nodeIntegration: false,
|
|
45
|
+
webviewTag: false, navigateOnDragDrop: false, backgroundThrottling: false,
|
|
46
|
+
preload: fileURLToPath(new URL('../assets/preload.cjs', import.meta.url))
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
this.window = win;
|
|
50
|
+
win.on('close', event => { event.preventDefault(); win.hide(); });
|
|
51
|
+
win.webContents.setWindowOpenHandler(() => ({ action: 'deny' }));
|
|
52
|
+
win.webContents.on('will-navigate', event => event.preventDefault());
|
|
53
|
+
win.on('closed', () => { this.window = undefined; this.dispose(); this.event('closed', {}); });
|
|
54
|
+
win.webContents.on('render-process-gone', () => this.dispose());
|
|
55
|
+
const htmlScript = (source) => '<script src="data:text/javascript;base64,' + Buffer.from(source).toString('base64') + '"></script>';
|
|
56
|
+
const html = '<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'none\'; script-src data:; style-src \'unsafe-inline\'; img-src data: blob:; connect-src \'none\'; object-src \'none\'; frame-src \'none\'; form-action \'none\'; base-uri \'none\'"><div id="plugin-root"></div>' + htmlScript(runtime) + htmlScript('globalThis.__ceruStart(' + code + ');');
|
|
57
|
+
await new Promise((resolve, reject) => {
|
|
58
|
+
const timer = setTimeout(() => { reject(new Error('Plugin activation timed out')); this.dispose(); }, 30000);
|
|
59
|
+
this.listener = (event, message) => {
|
|
60
|
+
if (event.sender !== win.webContents || !message || typeof message !== 'object')
|
|
61
|
+
return;
|
|
62
|
+
const { type, data } = message;
|
|
63
|
+
if (type === 'ready') {
|
|
64
|
+
void this.send('init', { generation: this.generation, mode: 'production', kind: surfaceId ? 'web' : 'logic', manifest: artifact.header.manifest, resources: artifact.resources, catalog: JSON.parse(catalog), mount: { kind: 'page' } });
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (message.generation !== this.generation)
|
|
68
|
+
return;
|
|
69
|
+
if (type === 'active') {
|
|
70
|
+
clearTimeout(timer);
|
|
71
|
+
if (surfaceId)
|
|
72
|
+
win.show();
|
|
73
|
+
resolve();
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
if (type === 'failed') {
|
|
77
|
+
clearTimeout(timer);
|
|
78
|
+
reject(new Error(String(data?.message || 'Plugin failed')));
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
if (type === 'invoke-result') {
|
|
82
|
+
const call = this.pending.get(data?.id);
|
|
83
|
+
if (!call)
|
|
84
|
+
return;
|
|
85
|
+
this.pending.delete(data.id);
|
|
86
|
+
clearTimeout(call.timer);
|
|
87
|
+
data.error ? call.reject(new Error(String(data.error))) : call.resolve(data.value);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
if (type === 'rpc') {
|
|
91
|
+
void this.rpc(String(data?.method), data?.data).then(value => this.send('rpc-result', { id: data.id, value }), error => this.send('rpc-result', { id: data.id, error: error instanceof Error ? error.message : 'Host request failed' })).catch(() => { });
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
this.event(type, data);
|
|
95
|
+
};
|
|
96
|
+
ipcMain.on('ceru:runtime', this.listener);
|
|
97
|
+
void win.loadURL('data:text/html;base64,' + Buffer.from(html).toString('base64')).catch(error => { clearTimeout(timer); reject(error); });
|
|
98
|
+
}).catch(error => { this.dispose(); throw error; });
|
|
99
|
+
}
|
|
100
|
+
send(type, data) {
|
|
101
|
+
if (!this.window || this.window.isDestroyed())
|
|
102
|
+
return Promise.reject(new Error('Plugin is stopped'));
|
|
103
|
+
return this.window.webContents.executeJavaScript('window.postMessage(' + JSON.stringify({ type, data, generation: this.generation }) + ', "*")').then(() => undefined);
|
|
104
|
+
}
|
|
105
|
+
show() { if (this.window && !this.window.isDestroyed()) {
|
|
106
|
+
this.window.show();
|
|
107
|
+
this.window.focus();
|
|
108
|
+
} }
|
|
109
|
+
invoke(kind, target, method, args, signal) {
|
|
110
|
+
const id = randomUUID();
|
|
111
|
+
return new Promise((resolve, reject) => {
|
|
112
|
+
const cancel = () => { this.pending.delete(id); void this.send('cancel', { id }).catch(() => { }); reject(new Error('Plugin operation cancelled')); };
|
|
113
|
+
const timer = setTimeout(cancel, 120000);
|
|
114
|
+
const done = () => { clearTimeout(timer); signal?.removeEventListener('abort', cancel); };
|
|
115
|
+
this.pending.set(id, { timer, resolve: value => { done(); resolve(value); }, reject: error => { done(); reject(error); } });
|
|
116
|
+
signal?.addEventListener('abort', cancel, { once: true });
|
|
117
|
+
if (signal?.aborted) {
|
|
118
|
+
done();
|
|
119
|
+
cancel();
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
void this.send('invoke', { id, kind, target, method, args }).catch(error => { this.pending.delete(id); done(); reject(error); });
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
dispose() {
|
|
126
|
+
if (this.listener)
|
|
127
|
+
ipcMain.removeListener('ceru:runtime', this.listener);
|
|
128
|
+
this.listener = undefined;
|
|
129
|
+
for (const call of this.pending.values()) {
|
|
130
|
+
clearTimeout(call.timer);
|
|
131
|
+
call.reject(new Error('Plugin stopped'));
|
|
132
|
+
}
|
|
133
|
+
this.pending.clear();
|
|
134
|
+
const win = this.window;
|
|
135
|
+
this.window = undefined;
|
|
136
|
+
if (win && !win.isDestroyed())
|
|
137
|
+
win.destroy();
|
|
138
|
+
}
|
|
139
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import { type ContentEntity, type JsonObject, type JsonValue, type OperationContext, type PluginContext, type PluginManifest, type ProviderImplementation } from '@shiqianjiang/ceru-plugin-sdk';
|
|
1
|
+
import { type ContentEntity, type JsonObject, type JsonValue, type OperationContext, type PluginContext, type PluginManifest, type ProviderImplementation, type LyricParseRequest, type LyricExportRequest } from '@shiqianjiang/ceru-plugin-sdk';
|
|
2
2
|
import { type Artifact, type ArtifactHeader } from '@shiqianjiang/ceru-plugin-issuer';
|
|
3
3
|
export interface CoreHostAdapter {
|
|
4
|
+
/** Real Host capabilities; absent services reject instead of pretending success. */
|
|
5
|
+
services?: Partial<PluginContext>;
|
|
4
6
|
/** Execute the bundled logic entry in the Host sandbox. */
|
|
5
7
|
activate(artifact: Artifact, context: PluginContext): Promise<void | (() => unknown)>;
|
|
6
8
|
/** Host-owned network broker. Playback URLs are returned directly. */
|
|
@@ -57,6 +59,7 @@ export interface CoreSnapshot {
|
|
|
57
59
|
providers: string[];
|
|
58
60
|
actions: string[];
|
|
59
61
|
importers: string[];
|
|
62
|
+
lyricConverters: string[];
|
|
60
63
|
}
|
|
61
64
|
/**
|
|
62
65
|
* Host-neutral v2 Core. The Core owns protocol dispatch and validation; a Host
|
|
@@ -71,6 +74,7 @@ export declare class PluginCore {
|
|
|
71
74
|
private readonly actions;
|
|
72
75
|
private readonly importers;
|
|
73
76
|
private disposers;
|
|
77
|
+
private converters;
|
|
74
78
|
private constructor();
|
|
75
79
|
static load(input: Uint8Array | ArrayBuffer | string, options: CoreOptions): Promise<PluginCore>;
|
|
76
80
|
context(): PluginContext;
|
|
@@ -82,6 +86,7 @@ export declare class PluginCore {
|
|
|
82
86
|
invokeAction(id: string, input?: JsonValue, operation?: OperationContext): Promise<JsonValue | void>;
|
|
83
87
|
importPlaylist(id: string, value: string, cursor?: string, limit?: number, operation?: OperationContext): Promise<any>;
|
|
84
88
|
dispose(): Promise<void>;
|
|
89
|
+
convertLyrics(id: string, method: 'parse' | 'export', request: LyricParseRequest | LyricExportRequest, operation?: OperationContext): Promise<any>;
|
|
85
90
|
snapshot(): CoreSnapshot;
|
|
86
91
|
}
|
|
87
92
|
export declare function readPluginArtifact(input: Uint8Array | ArrayBuffer | string): {
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import { assertContentPage, assertLyricsDocument, assertResolveResult, } from '@shiqianjiang/ceru-plugin-sdk';
|
|
1
|
+
import { assertContentPage, assertLyricsDocument, assertResolveResult, createHttpClient, } from '@shiqianjiang/ceru-plugin-sdk';
|
|
2
2
|
import { readArtifact, resolveArtifactConfig, } from '@shiqianjiang/ceru-plugin-issuer';
|
|
3
3
|
function methodAt(value, path) {
|
|
4
|
+
if (!/^(tracks\.(search|resolve|lyrics|artwork|suggest|hotSearch)|playlists\.(search|categories|list|get)|charts\.(list|getTracks)|sharing\.describe)$/.test(path))
|
|
5
|
+
throw new Error('Unsupported provider method: ' + path);
|
|
4
6
|
const parts = path.split('.');
|
|
5
7
|
const owner = parts.slice(0, -1).reduce((current, key) => current?.[key], value);
|
|
6
8
|
const method = owner?.[parts.at(-1)];
|
|
@@ -18,7 +20,6 @@ function operationOrDefault(operation) {
|
|
|
18
20
|
id: `core-${Date.now()}`,
|
|
19
21
|
deadlineAt: Date.now() + 30_000,
|
|
20
22
|
signal: controller.signal,
|
|
21
|
-
userIntent: { kind: 'user-intent', id: `core-${Date.now()}` },
|
|
22
23
|
};
|
|
23
24
|
}
|
|
24
25
|
/**
|
|
@@ -34,6 +35,7 @@ export class PluginCore {
|
|
|
34
35
|
actions = new Map();
|
|
35
36
|
importers = new Map();
|
|
36
37
|
disposers = [];
|
|
38
|
+
converters = new Map();
|
|
37
39
|
constructor(artifact, options) {
|
|
38
40
|
this.artifact = artifact;
|
|
39
41
|
this.manifest = artifact.header.manifest;
|
|
@@ -49,13 +51,18 @@ export class PluginCore {
|
|
|
49
51
|
const bytes = typeof input === 'string' ? new TextEncoder().encode(input) : input instanceof ArrayBuffer ? new Uint8Array(input) : input;
|
|
50
52
|
const artifact = readArtifact(bytes);
|
|
51
53
|
const core = new PluginCore(artifact, options);
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
54
|
+
try {
|
|
55
|
+
const dispose = await options.host.activate(artifact, core.context());
|
|
56
|
+
if (typeof dispose === 'function')
|
|
57
|
+
core.disposers.push(dispose);
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
await core.dispose();
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
55
63
|
return core;
|
|
56
64
|
}
|
|
57
65
|
context() {
|
|
58
|
-
const core = this;
|
|
59
66
|
const context = {
|
|
60
67
|
plugin: { id: this.manifest.id, version: this.manifest.version, manifest: this.manifest },
|
|
61
68
|
host: { apiVersion: '2.0.0', libraries: { lodash: 'host', icons: 'host', assets: 'host' }, mode: 'production' },
|
|
@@ -67,6 +74,12 @@ export class PluginCore {
|
|
|
67
74
|
providers: { register: (id, implementation) => this.registerProvider(id, implementation) },
|
|
68
75
|
actions: { register: (id, handler) => this.registerAction(id, handler) },
|
|
69
76
|
playlistImporters: { register: (id, implementation) => this.registerImporter(id, implementation) },
|
|
77
|
+
lyricConverters: { register: (id, implementation) => {
|
|
78
|
+
if (!this.manifest.contributes?.lyricConverters?.some(item => item.id === id))
|
|
79
|
+
throw new Error('Undeclared lyric converter');
|
|
80
|
+
this.converters.set(id, implementation);
|
|
81
|
+
return () => this.converters.delete(id);
|
|
82
|
+
} },
|
|
70
83
|
effects: { add: (dispose) => { this.disposers.push(dispose); } },
|
|
71
84
|
http: {
|
|
72
85
|
request: (request) => this.request(request),
|
|
@@ -79,6 +92,18 @@ export class PluginCore {
|
|
|
79
92
|
ui: { toast: async (message) => this.options.host.onNotice?.({ type: 'toast', data: message }), notify: async (message) => this.options.host.onNotice?.({ type: 'notify', data: message }) },
|
|
80
93
|
log: { debug: () => undefined, info: () => undefined, warn: () => undefined, error: () => undefined },
|
|
81
94
|
};
|
|
95
|
+
const services = this.options.host.services ?? {};
|
|
96
|
+
for (const [key, value] of Object.entries(services)) {
|
|
97
|
+
if (['plugin', 'providers', 'actions', 'playlistImporters', 'lyricConverters', 'effects'].includes(key))
|
|
98
|
+
throw new Error('Host cannot override Core registry: ' + key);
|
|
99
|
+
context[key] = value;
|
|
100
|
+
}
|
|
101
|
+
for (const name of ['library', 'account', 'player', 'queue', 'downloads', 'files', 'clipboard', 'settings', 'window', 'sharing', 'rooms', 'ai', 'tasks', 'sockets', 'events', 'guests', 'storage']) {
|
|
102
|
+
if (!context[name])
|
|
103
|
+
context[name] = new Proxy({}, { get: () => { throw new Error('Host service is not connected: ' + name); } });
|
|
104
|
+
}
|
|
105
|
+
if (!services.http)
|
|
106
|
+
context.http.create = (defaults) => createHttpClient(context, defaults);
|
|
82
107
|
return context;
|
|
83
108
|
}
|
|
84
109
|
registerProvider(id, implementation) {
|
|
@@ -108,21 +133,37 @@ export class PluginCore {
|
|
|
108
133
|
async request(input) {
|
|
109
134
|
if (!this.options.host.request)
|
|
110
135
|
throw new Error('Host HTTP service is not connected');
|
|
136
|
+
const declaration = this.manifest.permissions?.find(item => item.key === input.permissionKey && item.name === 'network.request');
|
|
137
|
+
if (!declaration)
|
|
138
|
+
throw new Error('Network permission is not declared');
|
|
139
|
+
const permissions = this.options.host.services?.permissions;
|
|
140
|
+
if (!permissions || (await permissions.query({ key: declaration.key })).status !== 'granted')
|
|
141
|
+
throw new Error('Network permission is not granted');
|
|
111
142
|
return this.options.host.request({ ...input, operation: operationOrDefault(input.operation) });
|
|
112
143
|
}
|
|
113
144
|
async invokeProvider(providerId, method, args = [], operation) {
|
|
145
|
+
const arities = { 'tracks.search': 1, 'tracks.resolve': 2, 'tracks.lyrics': 1, 'tracks.artwork': 1, 'tracks.suggest': 1, 'tracks.hotSearch': 0, 'playlists.search': 1, 'playlists.categories': 0, 'playlists.list': 2, 'playlists.get': 2, 'charts.list': 0, 'charts.getTracks': 2, 'sharing.describe': 2 };
|
|
146
|
+
const arity = arities[method];
|
|
147
|
+
if (arity === undefined || !Array.isArray(args) || args.length > arity)
|
|
148
|
+
throw new Error(`Invalid ${method} arguments: expected ${arity ?? 'a supported method'}`);
|
|
149
|
+
const input = [...args];
|
|
150
|
+
while (input.length < arity)
|
|
151
|
+
input.push(undefined);
|
|
114
152
|
const provider = this.providers.get(providerId);
|
|
115
153
|
if (!provider)
|
|
116
154
|
throw new Error(`Provider ${providerId} is not registered`);
|
|
117
155
|
const fn = methodAt(provider, method);
|
|
118
156
|
if (!fn)
|
|
119
157
|
throw new Error(`Provider ${providerId} does not implement ${method}`);
|
|
120
|
-
const
|
|
158
|
+
const op = operationOrDefault(operation);
|
|
159
|
+
op.signal.throwIfAborted();
|
|
160
|
+
const result = await fn(...input, op);
|
|
161
|
+
op.signal.throwIfAborted();
|
|
121
162
|
if (method === 'tracks.resolve' || method === 'resolve')
|
|
122
163
|
assertResolveResult(result);
|
|
123
164
|
else if (method === 'tracks.lyrics' || method === 'lyrics')
|
|
124
165
|
assertLyricsDocument(result);
|
|
125
|
-
else if (
|
|
166
|
+
else if (['tracks.search', 'playlists.search', 'playlists.categories', 'playlists.list', 'playlists.get', 'charts.list', 'charts.getTracks'].includes(method))
|
|
126
167
|
assertContentPage(result);
|
|
127
168
|
return result;
|
|
128
169
|
}
|
|
@@ -139,14 +180,31 @@ export class PluginCore {
|
|
|
139
180
|
throw new Error(`Playlist importer ${id} is not registered`);
|
|
140
181
|
const result = await importer.getTracks({ value, cursor, limit }, operationOrDefault(operation));
|
|
141
182
|
assertContentPage(result);
|
|
183
|
+
if (result.items.some(item => item.ref.kind !== 'track'))
|
|
184
|
+
throw new Error('Importers must return tracks');
|
|
142
185
|
return result;
|
|
143
186
|
}
|
|
144
187
|
async dispose() {
|
|
145
|
-
|
|
146
|
-
await dispose();
|
|
188
|
+
await Promise.allSettled(this.disposers.splice(0).reverse().map(dispose => Promise.resolve().then(dispose)));
|
|
147
189
|
this.providers.clear();
|
|
148
190
|
this.actions.clear();
|
|
149
191
|
this.importers.clear();
|
|
192
|
+
this.converters.clear();
|
|
193
|
+
}
|
|
194
|
+
async convertLyrics(id, method, request, operation) {
|
|
195
|
+
const converter = this.converters.get(id);
|
|
196
|
+
if (!converter || !['parse', 'export'].includes(method))
|
|
197
|
+
throw new Error('Lyric converter unavailable');
|
|
198
|
+
if (method === 'export')
|
|
199
|
+
assertLyricsDocument(request.document);
|
|
200
|
+
else if (typeof request.text !== 'string' || request.text.length > 2 * 1024 * 1024)
|
|
201
|
+
throw new Error('Invalid lyric input');
|
|
202
|
+
const result = await converter[method](request, operationOrDefault(operation));
|
|
203
|
+
if (method === 'parse')
|
|
204
|
+
assertLyricsDocument(result);
|
|
205
|
+
else if (!result || !['lrc', 'enhanced-lrc', 'yrc'].includes(result.format) || result.format !== request.format || typeof result.text !== 'string' || result.text.length > 2 * 1024 * 1024 || result.extension !== (result.format === 'enhanced-lrc' ? 'lrc' : result.format))
|
|
206
|
+
throw new Error('Invalid exported lyric text');
|
|
207
|
+
return result;
|
|
150
208
|
}
|
|
151
209
|
snapshot() {
|
|
152
210
|
return {
|
|
@@ -155,6 +213,7 @@ export class PluginCore {
|
|
|
155
213
|
providers: [...this.providers.keys()],
|
|
156
214
|
actions: [...this.actions.keys()],
|
|
157
215
|
importers: [...this.importers.keys()],
|
|
216
|
+
lyricConverters: [...this.converters.keys()],
|
|
158
217
|
};
|
|
159
218
|
}
|
|
160
219
|
}
|
package/dist/network.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import axios from 'axios';
|
|
2
|
+
import { Agent as HttpAgent } from 'node:http';
|
|
3
|
+
import { Agent as HttpsAgent } from 'node:https';
|
|
4
|
+
import { lookup } from 'node:dns/promises';
|
|
5
|
+
import { isIP } from 'node:net';
|
|
6
|
+
export function isPrivateAddress(address) {
|
|
7
|
+
const value = address.toLowerCase();
|
|
8
|
+
if (value.startsWith('::ffff:')) {
|
|
9
|
+
const tail = value.slice(7);
|
|
10
|
+
if (tail.includes('.'))
|
|
11
|
+
return isPrivateAddress(tail);
|
|
12
|
+
const words = tail.split(':').map(part => parseInt(part, 16));
|
|
13
|
+
return isPrivateAddress([words[0] >> 8, words[0] & 255, words[1] >> 8, words[1] & 255].join('.'));
|
|
14
|
+
}
|
|
15
|
+
if (value.includes(':'))
|
|
16
|
+
return !/^[23][0-9a-f]{3}:/.test(value);
|
|
17
|
+
const [a, b] = value.split('.').map(Number);
|
|
18
|
+
return a === 0 || a === 10 || a === 127 || a >= 224 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127);
|
|
19
|
+
}
|
|
20
|
+
export async function requestNetwork(input, privateAllowed, signal, redirects = 0) {
|
|
21
|
+
const url = new URL(input.url);
|
|
22
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password)
|
|
23
|
+
throw new Error('只支持 HTTP/HTTPS 请求');
|
|
24
|
+
const hostname = url.hostname.replace(/^\[|\]$/g, '');
|
|
25
|
+
const addresses = isIP(hostname) ? [{ address: hostname, family: isIP(hostname) }] : await lookup(hostname, { all: true });
|
|
26
|
+
if (!addresses.length)
|
|
27
|
+
throw new Error('无法解析服务器地址');
|
|
28
|
+
if (addresses.some(item => isPrivateAddress(item.address)) && !privateAllowed())
|
|
29
|
+
throw new Error('请先授予局域网访问权限');
|
|
30
|
+
const chosen = addresses[0];
|
|
31
|
+
const pin = ((_hostname, options, callback) => options?.all ? callback(null, [chosen]) : callback(null, chosen.address, chosen.family));
|
|
32
|
+
const httpAgent = new HttpAgent({ lookup: pin });
|
|
33
|
+
const httpsAgent = new HttpsAgent({ lookup: pin });
|
|
34
|
+
const headers = {};
|
|
35
|
+
for (const [name, value] of Object.entries(input.headers ?? {})) {
|
|
36
|
+
if (/^(host|connection|content-length|transfer-encoding|proxy-.*|upgrade)$/i.test(name))
|
|
37
|
+
continue;
|
|
38
|
+
if (typeof value !== 'string' || /[\r\n]/.test(value))
|
|
39
|
+
throw new Error('Invalid HTTP header');
|
|
40
|
+
headers[name] = value;
|
|
41
|
+
}
|
|
42
|
+
try {
|
|
43
|
+
const response = await axios.request({ url: url.href, method: input.method ?? 'GET', headers, data: input.body, httpAgent, httpsAgent, proxy: false, maxRedirects: 0, timeout: Math.min(60000, Math.max(1000, input.timeoutMs || 30000)), maxContentLength: 16 * 1024 * 1024, maxBodyLength: 4 * 1024 * 1024, responseType: 'arraybuffer', validateStatus: () => true, signal });
|
|
44
|
+
if ([301, 302, 303, 307, 308].includes(response.status) && response.headers.location) {
|
|
45
|
+
if (redirects >= 5)
|
|
46
|
+
throw new Error('重定向次数过多');
|
|
47
|
+
const next = new URL(response.headers.location, url);
|
|
48
|
+
if (next.origin !== url.origin)
|
|
49
|
+
for (const name of Object.keys(headers))
|
|
50
|
+
if (/authorization|cookie|token|key/i.test(name))
|
|
51
|
+
delete headers[name];
|
|
52
|
+
const method = response.status === 303 || ([301, 302].includes(response.status) && input.method === 'POST') ? 'GET' : input.method;
|
|
53
|
+
return requestNetwork({ ...input, url: next.href, headers, method, body: method === 'GET' ? undefined : input.body }, privateAllowed, signal, redirects + 1);
|
|
54
|
+
}
|
|
55
|
+
const raw = Buffer.from(response.data).toString('utf8');
|
|
56
|
+
let body = raw;
|
|
57
|
+
try {
|
|
58
|
+
body = JSON.parse(raw);
|
|
59
|
+
}
|
|
60
|
+
catch { }
|
|
61
|
+
return { status: response.status, headers: Object.fromEntries(Object.entries(response.headers).filter(([, v]) => v != null).map(([k, v]) => [k, String(v)])), body };
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
if (axios.isAxiosError(error))
|
|
65
|
+
throw new Error('网络请求失败: ' + (error.code ?? 'NETWORK_ERROR'));
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
finally {
|
|
69
|
+
httpAgent.destroy();
|
|
70
|
+
httpsAgent.destroy();
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import vm from 'node:vm';
|
|
2
|
+
import { parentPort } from 'node:worker_threads';
|
|
3
|
+
import { readFile } from 'node:fs/promises';
|
|
4
|
+
import { randomBytes, randomUUID } from 'node:crypto';
|
|
5
|
+
const timers = new Map();
|
|
6
|
+
let context;
|
|
7
|
+
let generation = '';
|
|
8
|
+
let messages = 0;
|
|
9
|
+
setInterval(() => { messages = 0; }, 1000).unref();
|
|
10
|
+
const deliver = (value) => vm.runInContext('globalThis.__receive(' + JSON.stringify(JSON.stringify(value)) + ')', context, { timeout: 5000 });
|
|
11
|
+
parentPort.on('message', async (message) => {
|
|
12
|
+
try {
|
|
13
|
+
if (message.type !== 'boot') {
|
|
14
|
+
if (context && message.generation === generation)
|
|
15
|
+
deliver(message);
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
generation = message.generation;
|
|
19
|
+
context = vm.createContext({ __bridge: (encoded) => {
|
|
20
|
+
try {
|
|
21
|
+
if (typeof encoded !== 'string' || encoded.length > 8 * 1024 * 1024)
|
|
22
|
+
throw new Error('Host message too large');
|
|
23
|
+
const { kind, value } = JSON.parse(encoded);
|
|
24
|
+
let result = null;
|
|
25
|
+
if (kind === 'message') {
|
|
26
|
+
if (++messages > 1000)
|
|
27
|
+
throw new Error('Plugin message rate exceeded');
|
|
28
|
+
parentPort.postMessage({ ...value, generation });
|
|
29
|
+
}
|
|
30
|
+
else if (kind === 'random') {
|
|
31
|
+
if (!Number.isInteger(value) || value < 0 || value > 65536)
|
|
32
|
+
throw new Error('Invalid random byte length');
|
|
33
|
+
result = [...randomBytes(value)];
|
|
34
|
+
}
|
|
35
|
+
else if (kind === 'url') {
|
|
36
|
+
const url = new URL(value.url, value.base);
|
|
37
|
+
if (value.search !== undefined)
|
|
38
|
+
url.search = value.search;
|
|
39
|
+
result = Object.fromEntries(['href', 'origin', 'protocol', 'hostname', 'host', 'port', 'username', 'password', 'pathname', 'hash', 'search'].map(key => [key, url[key]]));
|
|
40
|
+
}
|
|
41
|
+
else if (kind === 'params') {
|
|
42
|
+
const params = new URLSearchParams(value.value);
|
|
43
|
+
const allowed = ['get', 'getAll', 'has', 'set', 'append', 'delete', 'sort', 'entries', 'toString'];
|
|
44
|
+
if (!allowed.includes(value.method))
|
|
45
|
+
throw new Error('Invalid URL operation');
|
|
46
|
+
result = params[value.method](...value.args);
|
|
47
|
+
if (value.method === 'entries')
|
|
48
|
+
result = [...params.entries()];
|
|
49
|
+
if (['set', 'append', 'delete', 'sort'].includes(value.method))
|
|
50
|
+
result = params.toString();
|
|
51
|
+
}
|
|
52
|
+
else if (kind === 'uuid')
|
|
53
|
+
result = randomUUID();
|
|
54
|
+
else if (kind === 'decode')
|
|
55
|
+
result = new TextDecoder(value.encoding).decode(Uint8Array.from(value.bytes));
|
|
56
|
+
else if (kind === 'timer') {
|
|
57
|
+
if (timers.size >= 256)
|
|
58
|
+
throw new Error('Plugin timer limit exceeded');
|
|
59
|
+
const callback = () => { if (!value.repeat)
|
|
60
|
+
timers.delete(value.id); try {
|
|
61
|
+
deliver({ type: 'timer', id: value.id });
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
parentPort.postMessage({ type: 'failed', generation, data: { message: String(error) } });
|
|
65
|
+
} };
|
|
66
|
+
timers.set(value.id, (value.repeat ? setInterval : setTimeout)(callback, Math.max(value.repeat ? 10 : 0, Math.min(Number(value.ms) || 0, 2147483647))));
|
|
67
|
+
}
|
|
68
|
+
else if (kind === 'clearTimer') {
|
|
69
|
+
clearTimeout(timers.get(value));
|
|
70
|
+
clearInterval(timers.get(value));
|
|
71
|
+
timers.delete(value);
|
|
72
|
+
}
|
|
73
|
+
else
|
|
74
|
+
throw new Error('Unknown Host operation');
|
|
75
|
+
return JSON.stringify({ value: result });
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
return JSON.stringify({ error: error instanceof Error ? error.message : 'Host operation failed' });
|
|
79
|
+
}
|
|
80
|
+
} }, { codeGeneration: { strings: false, wasm: false } });
|
|
81
|
+
const [globals, runtime, catalog] = await Promise.all(['node-globals.js', 'sandbox.js', 'catalog.json'].map(name => readFile(new URL('../assets/' + name, import.meta.url), 'utf8')));
|
|
82
|
+
vm.runInContext(globals, context, { timeout: 5000 });
|
|
83
|
+
vm.runInContext(runtime, context, { timeout: 5000 });
|
|
84
|
+
deliver({ type: 'init', data: { generation, kind: 'logic', mode: 'production', manifest: message.manifest, resources: message.resources, catalog: JSON.parse(catalog) } });
|
|
85
|
+
vm.runInContext('globalThis.__ceruStart(' + message.entry + ')', context, { timeout: 5000 });
|
|
86
|
+
}
|
|
87
|
+
catch (error) {
|
|
88
|
+
parentPort.postMessage({ type: 'failed', generation, data: { message: error instanceof Error ? error.message : String(error) } });
|
|
89
|
+
}
|
|
90
|
+
});
|
package/dist/node.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { Artifact } from '@shiqianjiang/ceru-plugin-issuer';
|
|
2
|
+
/** Node worker + realm-local SDK. No Node modules or host objects enter plugin globals. */
|
|
3
|
+
export declare class NodePluginSandbox {
|
|
4
|
+
private readonly rpc;
|
|
5
|
+
private readonly event;
|
|
6
|
+
private worker?;
|
|
7
|
+
private generation;
|
|
8
|
+
private pending;
|
|
9
|
+
constructor(rpc: (method: string, data: any) => Promise<any>, event: (type: string, data: any) => void);
|
|
10
|
+
start(artifact: Artifact): Promise<void>;
|
|
11
|
+
send(type: string, data: any): Promise<void>;
|
|
12
|
+
invoke(kind: string, target: string, method: string, args: any[], signal?: AbortSignal, operationId?: string): Promise<any>;
|
|
13
|
+
dispose(): void;
|
|
14
|
+
}
|
package/dist/node.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { Worker } from 'node:worker_threads';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
/** Node worker + realm-local SDK. No Node modules or host objects enter plugin globals. */
|
|
4
|
+
export class NodePluginSandbox {
|
|
5
|
+
rpc;
|
|
6
|
+
event;
|
|
7
|
+
worker;
|
|
8
|
+
generation = randomUUID();
|
|
9
|
+
pending = new Map();
|
|
10
|
+
constructor(rpc, event) {
|
|
11
|
+
this.rpc = rpc;
|
|
12
|
+
this.event = event;
|
|
13
|
+
}
|
|
14
|
+
async start(artifact) {
|
|
15
|
+
const entry = artifact.header.manifest.modules.logic?.entry;
|
|
16
|
+
if (!entry)
|
|
17
|
+
return;
|
|
18
|
+
const worker = new Worker(new URL('./node-worker.js', import.meta.url), { execArgv: [], resourceLimits: { maxOldGenerationSizeMb: 128, maxYoungGenerationSizeMb: 32, stackSizeMb: 4 } });
|
|
19
|
+
this.worker = worker;
|
|
20
|
+
await new Promise((resolve, reject) => {
|
|
21
|
+
const timer = setTimeout(() => { reject(new Error('Plugin activation timed out')); this.dispose(); }, 30000);
|
|
22
|
+
worker.on('error', error => { clearTimeout(timer); reject(error); this.dispose(); });
|
|
23
|
+
worker.on('exit', () => { clearTimeout(timer); reject(new Error('Plugin runtime stopped')); this.dispose(); this.event('closed', {}); });
|
|
24
|
+
worker.on('message', message => {
|
|
25
|
+
if (message?.generation !== this.generation)
|
|
26
|
+
return;
|
|
27
|
+
const { type, data } = message;
|
|
28
|
+
try {
|
|
29
|
+
if (type === 'active') {
|
|
30
|
+
clearTimeout(timer);
|
|
31
|
+
resolve();
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
if (type === 'failed') {
|
|
35
|
+
clearTimeout(timer);
|
|
36
|
+
reject(new Error(String(data.message)));
|
|
37
|
+
this.dispose();
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
if (type === 'rpc') {
|
|
41
|
+
void this.rpc(String(data.method), data.data).then(value => this.send('rpc-result', { id: data.id, value }), error => this.send('rpc-result', { id: data.id, error: error instanceof Error ? error.message : 'Host request failed' })).catch(() => { });
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
if (type === 'invoke-result') {
|
|
45
|
+
const call = this.pending.get(data.id);
|
|
46
|
+
if (!call)
|
|
47
|
+
return;
|
|
48
|
+
this.pending.delete(data.id);
|
|
49
|
+
clearTimeout(call.timer);
|
|
50
|
+
data.error ? call.reject(new Error(String(data.error))) : call.resolve(data.value);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
this.event(type, data);
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
clearTimeout(timer);
|
|
57
|
+
reject(error);
|
|
58
|
+
this.dispose();
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
worker.postMessage({ type: 'boot', generation: this.generation, manifest: artifact.header.manifest, resources: artifact.resources, entry: artifact.modules[entry] });
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
async send(type, data) { this.worker?.postMessage({ type, data, generation: this.generation }); }
|
|
65
|
+
invoke(kind, target, method, args, signal, operationId) {
|
|
66
|
+
const id = operationId ?? randomUUID();
|
|
67
|
+
return new Promise((resolve, reject) => {
|
|
68
|
+
if (!this.worker) {
|
|
69
|
+
reject(new Error('Plugin runtime is not active'));
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
const cancel = () => { void this.send('cancel', { id }); done(); this.pending.delete(id); reject(new Error('Plugin operation cancelled')); };
|
|
73
|
+
const timer = setTimeout(() => { cancel(); this.dispose(); }, 120000);
|
|
74
|
+
const done = () => { clearTimeout(timer); signal?.removeEventListener('abort', cancel); };
|
|
75
|
+
this.pending.set(id, { timer, resolve: value => { done(); resolve(value); }, reject: error => { done(); reject(error); } });
|
|
76
|
+
signal?.addEventListener('abort', cancel, { once: true });
|
|
77
|
+
if (signal?.aborted) {
|
|
78
|
+
cancel();
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
void this.send('invoke', { id, kind, target, method, args });
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
dispose() {
|
|
85
|
+
const worker = this.worker;
|
|
86
|
+
this.worker = undefined;
|
|
87
|
+
for (const call of this.pending.values()) {
|
|
88
|
+
clearTimeout(call.timer);
|
|
89
|
+
call.reject(new Error('Plugin runtime stopped'));
|
|
90
|
+
}
|
|
91
|
+
this.pending.clear();
|
|
92
|
+
void worker?.terminate();
|
|
93
|
+
}
|
|
94
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
interface SocketEvent {
|
|
2
|
+
id: string;
|
|
3
|
+
event: string;
|
|
4
|
+
data: unknown;
|
|
5
|
+
}
|
|
6
|
+
/** Network libraries live in the Host. Plugins receive bounded JSON events and opaque handles. */
|
|
7
|
+
export declare class SocketBroker {
|
|
8
|
+
private readonly connections;
|
|
9
|
+
private events;
|
|
10
|
+
private generation;
|
|
11
|
+
private connecting;
|
|
12
|
+
connect(input: any, privateAllowed: boolean, reservedPorts: number[]): Promise<{
|
|
13
|
+
id: string;
|
|
14
|
+
}>;
|
|
15
|
+
private push;
|
|
16
|
+
send(id: string, event: string, data: unknown): void;
|
|
17
|
+
private release;
|
|
18
|
+
disconnect(id: string): void;
|
|
19
|
+
revoke(key: string): void;
|
|
20
|
+
closeAll(): void;
|
|
21
|
+
drain(): SocketEvent[];
|
|
22
|
+
}
|
|
23
|
+
export {};
|