仰望星辰工作室

starmusic-mobile

starmusic-mobile/ common/user-api/sandbox.js 12.0 KB · 343 行 原始文件
1/**
2 * 自定义源沙箱(迁移自 lx-music-mobile/src/core/init/userApi + android preload.js)
3 *
4 * 设计说明:
5 * - 预加载脚本(构建 globalThis.lx)与用户脚本在隔离函数作用域内执行(new Function),
6 * 避免污染宿主全局;通过注入的 lx 对象完成 on/send/request 双向通信。
7 * - H5 与 App 逻辑层均支持 new Function 与 uni.request,故采用统一实现;
8 * setTimeout/console 等宿主 API 可直接使用。
9 * - 脚本执行使用字符串拼接 + new Function 包裹,避免模板字符串包裹导致语法错误。
10 */
11import * as cryptoUtils from '../crypto.js'
12import { httpFetch } from '../music-sdk/request.js'
13import { addLog } from './logger.js'
14
15// globalThis polyfill(App 环境兼容)
16if (typeof globalThis === 'undefined') {
17 globalThis = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {}
18}
19
20let scriptActionHandler = null
21let currentLx = null
22let currentScriptInfo = null
23
24const EVENT_NAMES = {
25 request: 'request',
26 inited: 'inited',
27 updateAlert: 'updateAlert',
28}
29
30/** 校验歌词返回结构 */
31const verifyLyricInfo = (info) => {
32 if (typeof info != 'object' || typeof info.lyric != 'string') throw new Error('failed')
33 if (info.lyric.length > 51200) throw new Error('failed')
34 return {
35 lyric: info.lyric,
36 tlyric: typeof info.tlyric == 'string' && info.tlyric.length < 5120 ? info.tlyric : null,
37 rlyric: typeof info.rlyric == 'string' && info.rlyric.length < 5120 ? info.rlyric : null,
38 lxlyric: typeof info.lxlyric == 'string' && info.lxlyric.length < 8192 ? info.lxlyric : null,
39 }
40}
41
42/** 构建 lx.utils 对象 */
43const buildUtils = () => ({
44 crypto: {
45 aesEncrypt(buffer, mode, key, iv) {
46 const data = buffer instanceof Uint8Array ? buffer : cryptoUtils.utf8ToBytes(String(buffer))
47 const k = key instanceof Uint8Array ? key : cryptoUtils.utf8ToBytes(String(key))
48 const v = iv ? (iv instanceof Uint8Array ? iv : cryptoUtils.utf8ToBytes(String(iv))) : null
49 return cryptoUtils.aesEncrypt(data, mode, k, v)
50 },
51 rsaEncrypt(buffer, key) {
52 const data = buffer instanceof Uint8Array ? buffer : cryptoUtils.utf8ToBytes(String(buffer))
53 return cryptoUtils.rsaEncrypt(data, String(key))
54 },
55 randomBytes(size) {
56 return cryptoUtils.randomBytes(size)
57 },
58 md5(str) {
59 // 与原项目一致:先 encodeURIComponent 再 md5
60 return cryptoUtils.md5(encodeURIComponent(String(str)))
61 },
62 },
63 buffer: {
64 from(input, encoding) {
65 if (typeof input === 'string') {
66 switch (encoding) {
67 case 'base64':
68 return new Uint8Array(cryptoUtils.b64ToBytes(input))
69 case 'hex':
70 return new Uint8Array(cryptoUtils.hexToBytes(input))
71 default:
72 return new Uint8Array(cryptoUtils.utf8ToBytes(input))
73 }
74 }
75 if (Array.isArray(input) || input instanceof Uint8Array) return new Uint8Array(input)
76 throw new Error('Unsupported input type')
77 },
78 bufToString(buf, format) {
79 if (buf instanceof Uint8Array || Array.isArray(buf)) {
80 switch (format) {
81 case 'base64':
82 return cryptoUtils.bytesToB64(buf)
83 case 'hex':
84 return cryptoUtils.bytesToHex(buf)
85 case 'binary':
86 return Array.from(buf).map((b) => String.fromCharCode(b)).join('')
87 case 'utf8':
88 case 'utf-8':
89 default:
90 return cryptoUtils.bytesToUtf8(buf)
91 }
92 }
93 throw new Error('Input is not a valid buffer')
94 },
95 },
96})
97
98/**
99 * 构建 globalThis.lx 对象
100 */
101const createLx = (info) => {
102 let requestHandler = null
103 let isInited = false
104 let isShowedUpdateAlert = false
105
106 const lx = {
107 EVENT_NAMES,
108 version: '2.0.0',
109 env: 'mobile',
110 currentScriptInfo: {
111 name: info.name || '',
112 description: info.description || '',
113 version: info.version || '',
114 author: info.author || '',
115 homepage: info.homepage || '',
116 rawScript: info.script || '',
117 },
118 utils: buildUtils(),
119
120 /**
121 * 日志输出(脚本侧使用)
122 * 脚本内调用 lx.log(...) 会记录到设置页的「自定义源运行日志」
123 */
124 log(...args) {
125 if (!scriptActionHandler) return
126 scriptActionHandler({ action: 'log', data: args })
127 },
128
129 /**
130 * HTTP 请求(脚本侧使用)
131 * 请求与结果会写入运行日志,便于排查脚本内部接口异常
132 * @returns 取消函数
133 */
134 request(url, options, callback) {
135 const requestKey = 'r' + Math.random().toString().substring(2)
136 const opts = options || {}
137 const startedAt = Date.now()
138 const method = ((opts && opts.method) || 'GET').toUpperCase()
139 const briefUrl = String(url).length > 120 ? String(url).substring(0, 120) + '…' : String(url)
140 const req = httpFetch(url, opts)
141 req.promise
142 .then((resp) => {
143 addLog('http', `${method} ${resp.statusCode || ''}`, `${briefUrl}(${Date.now() - startedAt}ms)`)
144 if (typeof callback == 'function') callback(null, resp, resp.body)
145 })
146 .catch((err) => {
147 addLog('error', `${method} 请求失败`, `${briefUrl} → ${(err && err.message) || '未知错误'}`)
148 if (typeof callback == 'function') callback(err, null, null)
149 })
150 return () => {
151 req.cancelHttp()
152 }
153 },
154
155 /**
156 * 事件注册(脚本侧使用)
157 */
158 on(eventName, handler) {
159 if (eventName !== EVENT_NAMES.request) {
160 return Promise.reject(new Error('The event is not supported: ' + eventName))
161 }
162 requestHandler = handler
163 return Promise.resolve()
164 },
165
166 /**
167 * 事件发送(脚本侧使用)
168 */
169 send(eventName, data) {
170 switch (eventName) {
171 case EVENT_NAMES.inited: {
172 if (isInited) return Promise.reject(new Error('Script is inited'))
173 isInited = true
174 handleInit(data)
175 return Promise.resolve()
176 }
177 case EVENT_NAMES.updateAlert: {
178 if (isShowedUpdateAlert) return Promise.reject(new Error('The update alert can only be called once.'))
179 isShowedUpdateAlert = true
180 if (scriptActionHandler) {
181 let log = data && data.log
182 let updateUrl = data && data.updateUrl
183 if (!log || typeof log != 'string') {
184 isShowedUpdateAlert = false
185 return Promise.reject(new Error('log is required.'))
186 }
187 if (log.length > 1024) log = log.substring(0, 1024) + '...'
188 if (updateUrl && !/^https?:\/\//.test(updateUrl)) updateUrl = null
189 scriptActionHandler({ action: 'showUpdateAlert', data: { log, updateUrl, name: info.name } })
190 }
191 return Promise.resolve()
192 }
193 default:
194 return Promise.reject(new Error('The event is not supported: ' + eventName))
195 }
196 },
197
198 /** 内部:获取脚本注册的 request 处理器 */
199 _getRequestHandler() {
200 return requestHandler
201 },
202 }
203
204 const handleInit = (data) => {
205 if (!data) {
206 if (scriptActionHandler) {
207 scriptActionHandler({ action: 'init', data: { id: info.id, info: null, status: false, errorMessage: 'Missing required parameter init info' } })
208 }
209 return
210 }
211 // 校验 sources(与 lxmusic 一致:完全采用脚本声明的 actions/qualitys,不做过滤)
212 const sourceInfo = { sources: {} }
213 try {
214 for (const source of Object.keys(data.sources || {})) {
215 const userSource = data.sources[source]
216 if (!userSource || userSource.type !== 'music') continue
217 sourceInfo.sources[source] = {
218 type: 'music',
219 actions: Array.isArray(userSource.actions) ? userSource.actions.slice() : [],
220 qualitys: Array.isArray(userSource.qualitys) ? userSource.qualitys.slice() : [],
221 }
222 }
223 } catch (error) {
224 if (scriptActionHandler) {
225 scriptActionHandler({ action: 'init', data: { id: info.id, info: null, status: false, errorMessage: error.message } })
226 }
227 return
228 }
229 if (scriptActionHandler) {
230 scriptActionHandler({ action: 'init', data: { id: info.id, info: sourceInfo, status: true } })
231 }
232 }
233
234 return lx
235}
236
237/**
238 * 加载脚本
239 * @param {object} info { id, name, description, version, author, homepage, script }
240 */
241export const loadScript = (info) => {
242 destroy()
243 currentScriptInfo = info
244 const lx = createLx(info)
245 currentLx = lx
246 globalThis.lx = lx
247
248 try {
249 // 用字符串拼接避免模板字符串包裹用户脚本导致语法错误
250 // 用 new Function 在隔离函数作用域执行,脚本内 globalThis.lx 指向注入对象
251 const runScript = new Function('globalThis', info.script + '\n')
252 runScript(globalThis)
253 } catch (err) {
254 console.error('[user api script error]', err)
255 addLog('error', `脚本执行异常:${info.name || info.id}`, err && err.message)
256 if (scriptActionHandler) {
257 scriptActionHandler({ action: 'init', data: { id: info.id, info: null, status: false, errorMessage: err.message } })
258 }
259 }
260}
261
262/**
263 * 宿主 → 脚本 动作(目前仅 request:请求 musicUrl/lyric/pic)
264 * @returns Promise
265 */
266export const sendAction = (action, data) => {
267 if (action !== 'request' || !currentLx) {
268 return Promise.reject(new Error('script not loaded'))
269 }
270 const handler = currentLx._getRequestHandler()
271 if (!handler) {
272 return Promise.reject(new Error('Request event is not defined'))
273 }
274 return new Promise((resolve, reject) => {
275 try {
276 handler
277 .call(globalThis.lx, { source: data.source, action: data.action, info: data.info })
278 .then((response) => {
279 let result
280 switch (data.action) {
281 case 'musicUrl':
282 if (typeof response != 'string' || response.length > 2048 || !/^https?:/.test(response)) {
283 console.error('[sandbox musicUrl invalid response]', typeof response, String(response).substring(0, 200))
284 addLog('error', 'musicUrl 返回值无效', `类型 ${typeof response}:${String(response).substring(0, 120)}`)
285 throw new Error('failed: musicUrl 返回值无效(需 http(s) 开头的字符串 URL)')
286 }
287 result = {
288 source: data.source,
289 action: data.action,
290 data: { type: data.info.type, url: response },
291 }
292 break
293 case 'lyric':
294 result = {
295 source: data.source,
296 action: data.action,
297 data: verifyLyricInfo(response),
298 }
299 break
300 case 'pic':
301 if (typeof response != 'string' || response.length > 2048 || !/^https?:/.test(response)) {
302 console.error('[sandbox pic invalid response]', typeof response, String(response).substring(0, 200))
303 throw new Error('failed: pic 返回值无效(需 http(s) 开头的字符串 URL)')
304 }
305 result = {
306 source: data.source,
307 action: data.action,
308 data: response,
309 }
310 break
311 default:
312 throw new Error('unknown action: ' + data.action)
313 }
314 resolve(result)
315 })
316 .catch((err) => {
317 console.error('[sandbox request failed]', data.source, data.action, err && err.message)
318 reject(new Error(err && err.message ? err.message : 'failed'))
319 })
320 } catch (err) {
321 console.error('[sandbox request throw]', data.source, data.action, err && err.message)
322 reject(new Error(err && err.message ? err.message : 'failed'))
323 }
324 })
325}
326
327/**
328 * 注册脚本 → 宿主 动作处理
329 * 动作:init / showUpdateAlert / log
330 */
331export const onScriptAction = (handler) => {
332 scriptActionHandler = handler
333}
334
335/** 销毁沙箱 */
336export const destroy = () => {
337 if (currentLx && globalThis.lx === currentLx) delete globalThis.lx
338 currentLx = null
339 currentScriptInfo = null
340}
341
342/** 获取当前加载的脚本信息 */
343export const getCurrentScriptInfo = () => currentScriptInfo