@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.
@@ -0,0 +1,229 @@
1
+ import { lookup } from 'node:dns/promises';
2
+ import { isIP } from 'node:net';
3
+ import { Agent as HttpAgent } from 'node:http';
4
+ import { Agent as HttpsAgent } from 'node:https';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { io } from 'socket.io-client';
7
+ import WebSocket from 'ws';
8
+ const privateAddress = (address) => {
9
+ const value = address.toLowerCase();
10
+ if (value.startsWith('::ffff:'))
11
+ return privateAddress(value.slice('::ffff:'.length));
12
+ if (value.includes(':'))
13
+ return (value === '::1' ||
14
+ value.startsWith('fc') ||
15
+ value.startsWith('fd') ||
16
+ value.startsWith('fe80'));
17
+ const parts = value.split('.').map(Number);
18
+ return (parts[0] === 0 ||
19
+ parts[0] === 10 ||
20
+ parts[0] === 127 ||
21
+ (parts[0] === 169 && parts[1] === 254) ||
22
+ (parts[0] === 100 && parts[1] >= 64 && parts[1] <= 127) ||
23
+ parts[0] >= 224 ||
24
+ (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) ||
25
+ (parts[0] === 192 && parts[1] === 168));
26
+ };
27
+ const reservedEvents = new Set([
28
+ 'connect',
29
+ 'connect_error',
30
+ 'disconnect',
31
+ 'disconnecting',
32
+ 'newListener',
33
+ 'removeListener',
34
+ 'error',
35
+ '__proto__',
36
+ 'constructor',
37
+ 'prototype',
38
+ ]);
39
+ /** Network libraries live in the Host. Plugins receive bounded JSON events and opaque handles. */
40
+ export class SocketBroker {
41
+ connections = new Map();
42
+ events = [];
43
+ generation = 0;
44
+ connecting = 0;
45
+ async connect(input, privateAllowed, reservedPorts) {
46
+ if (this.connections.size + this.connecting >= 8)
47
+ throw new Error('Socket connection limit reached');
48
+ this.connecting++;
49
+ const generation = this.generation;
50
+ try {
51
+ const kind = input.kind;
52
+ if (!['websocket', 'socket.io'].includes(kind))
53
+ throw new Error('Unknown socket protocol');
54
+ const url = new URL(input.url);
55
+ if (url.username ||
56
+ url.password ||
57
+ url.hash ||
58
+ (kind === 'websocket'
59
+ ? !['ws:', 'wss:'].includes(url.protocol)
60
+ : !['http:', 'https:'].includes(url.protocol)))
61
+ throw new Error('Unsupported socket URL');
62
+ const path = kind === 'socket.io' ? String(input.path || '/socket.io/') : url.pathname;
63
+ if (!path.startsWith('/') || path.startsWith('//') || /[?#\\]|%(?:2f|5c)/i.test(path))
64
+ throw new Error('Invalid socket path');
65
+ const hostname = url.hostname.replace(/^\[|\]$/g, '');
66
+ const addresses = isIP(hostname)
67
+ ? [{ address: hostname, family: isIP(hostname) }]
68
+ : await lookup(hostname, { all: true });
69
+ if (!addresses.length)
70
+ throw new Error('No socket address found');
71
+ if (addresses.some((item) => privateAddress(item.address)) && !privateAllowed)
72
+ throw new Error('Private network access is not granted');
73
+ const defaultPort = ['https:', 'wss:'].includes(url.protocol) ? 443 : 80;
74
+ if (reservedPorts.includes(Number(url.port) || defaultPort))
75
+ throw new Error('Development ports are reserved');
76
+ const chosen = addresses[0];
77
+ const Agent = ['https:', 'wss:'].includes(url.protocol) ? HttpsAgent : HttpAgent;
78
+ const agent = new Agent({
79
+ lookup: ((_hostname, options, callback) => options?.all
80
+ ? callback(null, [chosen])
81
+ : callback(null, chosen.address, chosen.family)),
82
+ });
83
+ const id = randomUUID();
84
+ let socket;
85
+ if (kind === 'socket.io') {
86
+ const auth = input.auth ?? {};
87
+ if (Buffer.byteLength(JSON.stringify(auth)) > 16384) {
88
+ agent.destroy();
89
+ throw new Error('Socket auth is too large');
90
+ }
91
+ socket = io(url.href, {
92
+ path,
93
+ auth,
94
+ autoConnect: false,
95
+ forceNew: true,
96
+ transports: ['websocket'],
97
+ upgrade: false,
98
+ reconnection: input.reconnection !== false,
99
+ reconnectionAttempts: 5,
100
+ reconnectionDelay: 1000,
101
+ reconnectionDelayMax: 10000,
102
+ timeout: 10000,
103
+ transportOptions: { websocket: { agent, followRedirects: false, maxPayload: 65536 } },
104
+ });
105
+ socket.on('connect', () => this.push(id, 'connect', null));
106
+ socket.on('disconnect', (reason) => this.push(id, 'disconnect', reason));
107
+ socket.on('connect_error', () => this.push(id, 'error', 'Socket.IO connection failed'));
108
+ socket.onAny((event, ...args) => this.push(id, String(event), args));
109
+ }
110
+ else {
111
+ socket = new WebSocket(url.href, {
112
+ agent,
113
+ followRedirects: false,
114
+ handshakeTimeout: 10000,
115
+ maxPayload: 65536,
116
+ });
117
+ socket.on('open', () => this.push(id, 'connect', null));
118
+ socket.on('close', (code) => {
119
+ this.push(id, 'disconnect', { code });
120
+ this.release(id);
121
+ });
122
+ socket.on('error', () => this.push(id, 'error', 'WebSocket connection failed'));
123
+ socket.on('message', (data, binary) => {
124
+ if (binary) {
125
+ this.push(id, 'error', 'Binary frames are not supported by this JSON channel');
126
+ return;
127
+ }
128
+ this.push(id, 'message', data.toString());
129
+ });
130
+ }
131
+ this.connections.set(id, {
132
+ key: String(input.permissionKey),
133
+ kind,
134
+ socket,
135
+ agent,
136
+ lastSend: Date.now(),
137
+ sends: 0,
138
+ });
139
+ if (generation !== this.generation) {
140
+ this.disconnect(id);
141
+ throw new Error('Plugin was stopped while connecting');
142
+ }
143
+ if (kind === 'socket.io')
144
+ socket.connect();
145
+ return { id };
146
+ }
147
+ finally {
148
+ this.connecting--;
149
+ }
150
+ }
151
+ push(id, event, data) {
152
+ if (!this.connections.has(id))
153
+ return;
154
+ let text;
155
+ try {
156
+ text = JSON.stringify(data ?? null);
157
+ }
158
+ catch {
159
+ this.disconnect(id);
160
+ return;
161
+ }
162
+ if (Buffer.byteLength(text) > 65536 || this.events.length >= 256) {
163
+ this.disconnect(id);
164
+ return;
165
+ }
166
+ this.events.push({ id, event, data: JSON.parse(text) });
167
+ }
168
+ send(id, event, data) {
169
+ const entry = this.connections.get(id);
170
+ if (!entry)
171
+ throw new Error('Socket is closed');
172
+ const text = JSON.stringify(data ?? null);
173
+ if (Buffer.byteLength(text) > 65536)
174
+ throw new Error('Socket message is too large');
175
+ if (Date.now() - entry.lastSend >= 1000) {
176
+ entry.lastSend = Date.now();
177
+ entry.sends = 0;
178
+ }
179
+ if (++entry.sends > 100)
180
+ throw new Error('Socket send rate exceeded');
181
+ if (entry.kind === 'socket.io') {
182
+ if (typeof event !== 'string' || event.length > 128 || reservedEvents.has(event))
183
+ throw new Error('Invalid Socket.IO event');
184
+ const socket = entry.socket;
185
+ if (!socket.connected)
186
+ throw new Error('Socket is not connected');
187
+ socket.emit(event, data);
188
+ }
189
+ else {
190
+ const socket = entry.socket;
191
+ if (socket.readyState !== WebSocket.OPEN)
192
+ throw new Error('Socket is not connected');
193
+ socket.send(typeof data === 'string' ? data : text);
194
+ }
195
+ }
196
+ release(id) {
197
+ const entry = this.connections.get(id);
198
+ this.connections.delete(id);
199
+ entry?.agent.destroy();
200
+ }
201
+ disconnect(id) {
202
+ const entry = this.connections.get(id);
203
+ if (!entry)
204
+ return;
205
+ this.connections.delete(id);
206
+ if (entry.kind === 'socket.io')
207
+ entry.socket.disconnect();
208
+ else
209
+ entry.socket.terminate();
210
+ entry.agent.destroy();
211
+ this.events = this.events.filter((event) => event.id !== id);
212
+ }
213
+ revoke(key) {
214
+ for (const [id, entry] of this.connections)
215
+ if (entry.key === key)
216
+ this.disconnect(id);
217
+ }
218
+ closeAll() {
219
+ this.generation++;
220
+ for (const id of this.connections.keys())
221
+ this.disconnect(id);
222
+ this.events = [];
223
+ }
224
+ drain() {
225
+ const events = this.events;
226
+ this.events = [];
227
+ return events;
228
+ }
229
+ }
package/package.json CHANGED
@@ -1,30 +1,63 @@
1
- {
2
- "name": "@shiqianjiang/ceru-plugin-core",
3
- "version": "0.2.0",
4
- "description": "Ceru Music v2 plugin Core runtime and Host adapter boundary",
5
- "type": "module",
6
- "main": "./dist/index.js",
7
- "types": "./dist/index.d.ts",
1
+ {
2
+ "name": "@shiqianjiang/ceru-plugin-core",
3
+ "version": "0.2.1",
4
+ "description": "Ceru Music v2 plugin Core runtime and Host adapter boundary",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
8
  "exports": {
9
- ".": {
10
- "types": "./dist/index.d.ts",
11
- "import": "./dist/index.js",
12
- "default": "./dist/index.js"
13
- }
14
- },
15
- "files": ["dist", "README.md", "LICENSE"],
16
- "license": "MIT",
17
- "author": "澜音团队",
18
- "engines": { "node": ">=22.12.0" },
9
+ "./sockets": { "types": "./dist/socket-broker.d.ts", "default": "./dist/socket-broker.js" },
10
+ "./node": {
11
+ "types": "./dist/node.d.ts",
12
+ "default": "./dist/node.js"
13
+ },
14
+ "./network": {
15
+ "types": "./dist/network.d.ts",
16
+ "default": "./dist/network.js"
17
+ },
18
+ "./electron": {
19
+ "types": "./dist/electron.d.ts",
20
+ "import": "./dist/electron.js",
21
+ "default": "./dist/electron.js"
22
+ },
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "import": "./dist/index.js",
26
+ "default": "./dist/index.js"
27
+ }
28
+ },
29
+ "files": [
30
+ "dist",
31
+ "assets",
32
+ "README.md",
33
+ "LICENSE",
34
+ "NOTICE"
35
+ ],
36
+ "license": "MIT AND AGPL-3.0-only",
37
+ "author": "澜音团队",
38
+ "engines": {
39
+ "node": ">=22.12.0"
40
+ },
19
41
  "dependencies": {
20
- "@shiqianjiang/ceru-plugin-issuer": "0.2.3",
21
- "@shiqianjiang/ceru-plugin-sdk": "0.2.3"
22
- },
23
- "publishConfig": { "access": "public", "registry": "https://registry.npmjs.org/" },
24
- "repository": {
25
- "type": "git",
26
- "url": "git+https://github.com/CeruMusic/CeruMusic-Plugin-Cli.git",
27
- "directory": "packages/core"
28
- },
29
- "keywords": ["ceru-music", "plugin", "core", "electron"]
30
- }
42
+ "socket.io-client": "^4.8.3",
43
+ "ws": "^8.21.3",
44
+ "axios": "^1.13.2",
45
+ "@shiqianjiang/ceru-plugin-issuer": "0.2.4",
46
+ "@shiqianjiang/ceru-plugin-sdk": "0.2.4"
47
+ },
48
+ "publishConfig": {
49
+ "access": "public",
50
+ "registry": "https://registry.npmjs.org/"
51
+ },
52
+ "repository": {
53
+ "type": "git",
54
+ "url": "git+https://github.com/CeruMusic/CeruMusic-Plugin-Cli.git",
55
+ "directory": "packages/core"
56
+ },
57
+ "keywords": [
58
+ "ceru-music",
59
+ "plugin",
60
+ "core",
61
+ "electron"
62
+ ]
63
+ }